题目来源
题目分析
不可以假设只有一个C或者两个C,可能有很多个C,因此不能简单变量来存储历史数据
栈
将各个回合的分数压入栈之后再求和
package com.oceanstar;
import java.util.Stack;
public class Solution {
public static int calPoints(String[] ops) {
int sum = 0;
Stack<Integer> stack = new Stack<>();
for (String s : ops){
switch (s){
// ops一定是正确的
case "+":
int a1 = stack.pop();
int a2 = stack.peek();
int a3 = a1 + a2;
stack.push(a1);
stack.push(a3);
break;
case "D":
// 后入先出
int a = stack.peek() * 2;
stack.push(a);
break;
case "C":
stack.pop();
break;
default:
stack.push(Integer.parseInt(s));
break;
}
}
for (int c : stack){
sum = sum + c;
}
return sum;
}
public static void main(String[] args) {
String[] ops = new String[]{"5","-2","4","C","D","9","+","+"};
System.out.println(calPoints(ops));
}
}