LeetCode150. 逆波兰表达式求值

class Solution {
    public int evalRPN(String[] tokens) {
        // 遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。
        Stack<Integer> stack = new Stack<>();
        int num;
        for (String s : tokens) {
            switch (s) {
                case "+":
                    stack.push(stack.pop() + stack.pop());
                    break;
                case "-":
                    num = stack.pop();
                    stack.push(stack.pop() - num);
                    break;
                case "*":
                    stack.push(stack.pop() * stack.pop());
                    break;
                case "/":
                    num = stack.pop();
                    stack.push(stack.pop() / num);
                    break;
                default:
                    stack.push(Integer.valueOf(s));
            }
        }
        return stack.pop();
    }
}
原文地址:https://www.cnblogs.com/HuangYJ/p/14155278.html