[leetcode]Evaluate Reverse Polish Notation

题目描述如下:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.

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/

你可能感兴趣的:(LeetCode)