題目地址:
https://www.lintcode.com/problem/baseball-game/description
給定一個字符串數組,代表計分的一系列操作:
1、整數 (一個回合的分數):直接表示這回合你得到的分數;
2、 (一個回合的分數):表示這回合你獲得的分數爲前兩個有效 分數之和;
3、 (一個回合的分數):表示這回合你得到的分數爲你上一次獲得的有效分數的兩倍;
4、 (一種操作,而非一個回合的分數):表示你上回合的有效分數是無效的,需要移除。
返回這一系列操作下後得到的總分。
直接用棧模擬即可。代碼如下:
import java.util.ArrayDeque;
import java.util.Deque;
public class Solution {
/**
* @param ops: the list of operations
* @return: the sum of the points you could get in all the rounds
*/
public int calPoints(String[] ops) {
// Write your code here
Deque<Integer> stack = new ArrayDeque<>();
for (String op : ops) {
if (op.equals("C")) {
stack.pop();
} else if (op.equals("D")) {
stack.push(2 * stack.peek());
} else if (op.equals("+")) {
int top = stack.pop(), next = stack.peek() + top;
stack.push(top);
stack.push(next);
} else {
stack.push(Integer.parseInt(op));
}
}
int res = 0;
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}
}
時空複雜度。