[leetcode]Evaluate Reverse Polish Notation

2759 ワード

タイトルは以下の通りです.
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
接尾辞式の計算について.
接尾辞式を理解していない場合は、接頭辞、接尾辞、接尾辞式を参照してください.
操作方法を知った後、この問題はシミュレーションプロセスであり、コードは以下の通りです.
public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<Integer>();
        int i, num, num1, num2;
        for (i = 0; i < tokens.length; i++) {
            if (!tokens[i].equals("+") && !tokens[i].equals("-") &&!tokens[i].equals("*") && !tokens[i].equals("/")) {
                stack.push(Integer.valueOf(tokens[i]));
            } else {
                num1 = stack.pop();
                num2 = stack.pop();
                switch(tokens[i]){
                    case "+": stack.push(num1 + num2); break;
                    case "-": stack.push(num2 - num1); break;
                    case "*": stack.push(num1 * num2); break;
                    case "/": stack.push(num2 / num1); break;
                }
            }
        }
        return stack.pop();
    }
}

接尾辞式をすばやく求める例を示します
a+b*(c+d/e)
(a+(b*(c+(d/e))計算順にかっこを付ける
(a(b(c(de)/+)*)+演算子をかっこの外に置く
abcde/+*+かっこを外す
タイトルリンク:https://leetcode.com/problems/evaluate-reverse-polish-notation/