150. Evaluate Reverse Polish Notation

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

一刷
用stack来解。碰到标点符号,连续弹出两个并进行运算并压栈,否则压栈。

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        int a, b;
        for(String s : tokens){
            if(s.equals("+")) stack.push(stack.pop() + stack.pop());
            else if(s.equals("/")){
                b = stack.pop();
                a = stack.pop();
                stack.push(a/b);
            }
            else if(s.equals("*")) stack.push(stack.pop() * stack.pop());
            else if(s.equals("-")){
                b = stack.pop();
                a = stack.pop();
                stack.push(a-b); 
            }
            else stack.push(Integer.parseInt(s));
        }
        return stack.pop();
    }
}

google原题,阶乘怎么处理

推荐阅读更多精彩内容