Leetcode 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

思路:

  1. 用栈记录数组前面未进行运算的值。
  2. 遍历数组。遇到数字直接入栈;遇到运算符号,出栈两个数字进行运算,将结果入栈。
  3. 最后返回栈中元素就是表达式计算结果。
  4. 注意除法和减法,出栈数字的运算顺序。
public int evalRPN(String[] tokens) {
    if (tokens == null || tokens.length == 0) {
        return 0;
    }

    Stack<Integer> stack = new Stack<>();
    for (String val : tokens) {
        if (val.equals("+")) {
            stack.push(stack.pop() + stack.pop());
        } else if (val.equals("-")) {
            int a = stack.pop();
            int b = stack.pop();
            stack.push(b - a);
        } else if (val.equals("*")) {
            stack.push(stack.pop() * stack.pop());
        } else if (val.equals("/")) {
            int a = stack.pop();
            int b = stack.pop();
            stack.push(b / a);
        } else if (Integer.valueOf(val) >= 0) {
            stack.push(Integer.valueOf(val));
        } else {
            return -1;
        }
    }

    return stack.pop();
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/9209368fbf4e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞