150. Evaluate Reverse Polish Notation

题目链接:https://leetcode.com/problems...

stack来做,保存数字,碰到符号的时候就弹出两个数字计算算完后再放入stack,最后stack里面的就是结果。

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack();
        for(String s : tokens) {
            // sign
            if(s.matches("[+-/*]")) {
                if(stack.size() < 2) throw new IllegalArgumentException("invalid expression");
                int num2 = stack.pop();
                int num1 = stack.pop();
                if(s.equals("+")) {
                    stack.push(num1+num2);
                }
                else if(s.equals("-")) {
                    stack.push(num1 - num2);
                }
                else if(s.equals("/")) {
                    if(num2 == 0) throw new IllegalArgumentException("divisor is 0");
                    stack.push(num1 / num2);
                }
                else {
                    stack.push(num1 * num2);
                }
            }
            else {
                stack.push(Integer.valueOf(s));
            }
        }
        if(stack.size() != 1) throw new IllegalArgumentException("invalid expression");
        return stack.pop();
    }
}

lulouch13
13 声望6 粉丝