150. Evaluate Reverse Polish Notation

Medium
这个Wikipedia的解释非常Helpful, 尤其下面那种讲清楚栈里面有什么的那张图表.
Reverse Polish notation

150. Evaluate Reverse Polish Notation_第1张图片
image.png

我的写法比较straightforward了,但是我居然忘记了如何判断String是不是valid integer的方法了,所以先把其他情况穷举完了.

class Solution {
    public int evalRPN(String[] tokens) {
        Stack stack = new Stack<>();
        for (String token : tokens){
            if (token.equals("+")){
                int num1 = stack.pop();
                int num2 = stack.pop();
                int sum = num1 + num2;
                stack.push(sum);
            } else if (token.equals("-")){
                int num1 = stack.pop();
                int num2 = stack.pop();
                int subs = num2 - num1;
                stack.push(subs);
            } else if (token.equals("*")){
                int num1 = stack.pop();
                int num2 = stack.pop();
                int prod = num1 * num2;
                stack.push(prod);
            } else if (token.equals("/")){
                int num1 = stack.pop();
                int num2 = stack.pop();
                int quot = num2 / num1;
                stack.push(quot);
            } else {
                int num = Integer.parseInt(token);
                stack.push(num);
            }
        }
        return stack.pop();
    }
}

你可能感兴趣的:(150. Evaluate Reverse Polish Notation)