Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
思路:就是用栈来实现后缀式也就是逆波兰式的计算过程
代码如下(已通过leetcode)
public class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack=new Stack<String>();
for(String s:tokens) {
if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/")) {
int dig2=Integer.parseInt(stack.pop());
int dig1=Integer.parseInt(stack.pop());
switch(s){
case "+":
stack.push(""+(dig1+dig2));
break;
case "-":
stack.push(""+(dig1-dig2));
break;
case "*":
stack.push(""+(dig1*dig2));
break;
case "/":
stack.push(""+(dig1/dig2));
break;
}
} else {
stack.push(s);
}
}
return Integer.parseInt(stack.pop());
}
}