题目链接:
力扣https://leetcode-cn.com/problems/baseball-game/
【分析】用栈来模拟就行,当然不用栈,开一个1001长度的数组也可以。
class Solution {
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
int n = ops.length, i, a, b;
String str;
for(i = 0; i < n; i++){
str = ops[i];
if(str.equals("+")){
a = stack.pop();
b = stack.peek();
stack.push(a);
stack.push(a + b);
}else if(str.equals("D")){
stack.push(stack.peek() * 2);
}else if(str.equals("C")){
stack.pop();
}else{
stack.push(Integer.parseInt(str));
}
}
int ans = 0;
while(!stack.empty()){
ans += stack.pop();
}
return ans;
}
}