682. [栈]棒球比赛
682. 棒球比赛
LinkedList 实现了 Queue, Deque, Stack 的功能,只需分别模拟 C, D, + 需要实现的计分规则即可。其中 + 操作可以理解为:先将top弹出,然后计算新栈顶的值为 newTop = top + 当前栈顶值,然后再依次入栈即可。
class Solution {
public int calPoints(String[] ops) {
LinkedList<Integer> stack = new LinkedList<>();
int sum = 0;
for(String op: ops){
if (op.equals("C")){
stack.pollLast();
} else if (op.equals("D")){
stack.offer(stack.peekLast()*2);
} else if (op.equals("+")){
int top = stack.pollLast();
int newTop = num1 + stack.peekLast();
stack.offer(top);
stack.offer(newTop);
} else {
stack.offer(Integer.parseInt(op));
}
}
for(int score: stack){
sum += score;
}
return sum;
}
}

浙公网安备 33010602011771号