leetcode150

Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
* Division between two integers should truncate toward zero.
* The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Stack.
1.看到数字压入stack。
2.看到运算符pop两个数字去运算,注意两个数字顺序要反一下。
3.返回最后剩下的数字。

细节:
1.快速判断是不是运算符,需要一个备用仓库,仓库用String operators = "+-*/“;来写,比用Set+四行初始化写要优雅。另外HashSet的构造器可以传参Collections类型的(set, list …),不可以传array。
2.Switch格式:外类if,然后 case “+” : …; break;

实现:

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        
        // P1: 这个仓库比用set写优雅很多。
        String operators = "+-*/";
        for (int i = 0; i < tokens.length; i++) {
            if (!operators.contains(tokens[i])) {
                stack.push(Integer.parseInt(tokens[i]));
            } else {
                int o1 = stack.pop();
                int o2 = stack.pop();
                // check API.
                switch (tokens[i]) {
                    case "+": stack.push(o2 + o1); break;
                    case "-": stack.push(o2 - o1); break;
                    case "*": stack.push(o2 * o1); break;
                    case "/": stack.push(o2 / o1); break;
                }
            }
        }
        return stack.peek();
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/9666251.html