leetcode150. Evaluate Reverse Polish Notation

来源:互联网 发布:济宁淘宝店卖什么的多 编辑:程序博客网 时间:2024/06/07 06:44

150. 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

解法一

后缀表达式,采用栈来解决,如果是数字则入栈;如果是运算符,将栈顶的两位数出栈,结合运算符运算后入栈。

// @Author taotao// @ComplexityTime O(n) @Space O(n)// @method 采用stack解决,注意字符串相等用equalspublic class Solution {    public int evalRPN(String[] tokens) {        if (tokens.length == 0 || tokens == null) { return 0; }        Stack<Integer> stack = new Stack<>();        for (int i = 0; i < tokens.length; i++) {            String str = tokens[i];            if (!str.equals("+") && !str.equals("-") && !str.equals("*") && !str.equals("/")) {                stack.push(Integer.parseInt(tokens[i]));            } else {                int param0 = stack.pop(), param1 = stack.pop(), temp = 0;                switch (tokens[i]) {                    case "+":                        temp = param1 + param0;                        break;                    case "-":                        temp = param1 - param0;                        break;                    case "*":                        temp = param1 * param0;                        break;                    case "/":                        temp = param1 / param0;                        break;                }                stack.push(temp);            }        }        return stack.pop();    }}

这里写图片描述

1 0