LeetCode每日一题:逆波兰式(后缀表达式)

问题描述

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

问题分析

首先明白逆波兰表达式(Reverse Polish Notation),也叫后缀表达式,每一运算符都置于其运算对象之后,故称为后缀表示。
很明显是用栈进行操作,对String遍历,

  • 如果是数字类,那么压入栈
  • 如果是运算符号的话,弹出栈中两个元素,进行加减法后再弹入栈
  • 最后运算结束后栈中仅剩一个元素,即为最后的结果

代码实现

public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<Integer>();
        int a, b;
        for (int i = 0; i < tokens.length; i++) {
            if (tokens[i].equals("+")) {
                b = stack.pop();//注意栈是先进后出
                a = stack.pop();
                stack.push(a + b);
            } else if (tokens[i].equals("-")) {
                b = stack.pop();//注意栈是先进后出
                a = stack.pop();
                stack.push(a - b);
            } else if (tokens[i].equals("*")) {
                b = stack.pop();//注意栈是先进后出
                a = stack.pop();
                stack.push(a * b);
            } else if (tokens[i].equals("/")) {
                b = stack.pop();//注意栈是先进后出
                a = stack.pop();
                stack.push(a / b);
            } else {
                int num = Integer.parseInt(tokens[i]);
                stack.push(num);
            }
        }
        return stack.pop();
    }

推荐阅读更多精彩内容