class Solution {
public int evalRPN(String[] tokens) {
if(tokens == null || tokens.length == 0) return 0;
Stack<Integer> stack = new Stack<>();
String operators = "+-*/";
for(int i = 0; i < tokens.length; i++) {
if(!operators.contains(tokens[i])) {
stack.push(Integer.valueOf(tokens[i]));
} else {
int s1 = stack.pop();
int s2 = stack.pop();
switch(tokens[i]) {
case "+":
stack.push(s2 + s1);
break;
case "-":
stack.push(s2 - s1);
break;
case "*":
stack.push(s2 * s1);
break;
case "/":
stack.push(s2 / s1);
break;
}
}
}
return stack.pop();
}
}
Evaluate Reverse Polish Notation
最新推荐文章于 2022-03-25 16:52:08 发布