【LeetCode】150. Evaluate Reverse Polish Notation 逆波兰表达式求值(Medium)(JAVA)

【LeetCode】150. Evaluate Reverse Polish Notation 逆波兰表达式求值(Medium)(JAVA)

题目地址: https://leetcode.com/problems/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.

Note:

Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.
Example 1:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation: 
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

题目大意

根据 逆波兰表示法,求表达式的值。

有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

  • 整数除法只保留整数部分。
  • 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

解题方法

  1. 看例子的计算过程就可以明白:先把数组按序存到列表里;每当遇到符号,就把列表的后两个值拿出来计算,再把结果存到列表里
  2. note: 因为给定的表达式总是有效的,所以不需要判断是否有效
  3. 因为是后进先出,所以用 queue 比较快
class Solution {
    public int evalRPN(String[] tokens) {
        if (tokens.length <= 0) return 0;
        LinkedList<Integer> list = new LinkedList<>();
        for (int i = 0; i < tokens.length; i++) {
            if ("+".equals(tokens[i]) || "-".equals(tokens[i]) || "*".equals(tokens[i]) || "/".equals(tokens[i])) {
                int second = list.removeLast();
                int first = list.removeLast();
                int cur = 0;
                if ("+".equals(tokens[i])) {
                    cur = first + second;
                } else if ("-".equals(tokens[i])) {
                    cur = first - second;
                } else if ("*".equals(tokens[i])) {
                    cur = first * second;
                } else if ("/".equals(tokens[i])) {
                    cur = first / second;
                }
                list.add(cur);
            } else {
                list.add(Integer.parseInt(tokens[i]));
            }
        }
        return list.get(0);
    }
}

执行耗时:6 ms,击败了89.35% 的Java用户
内存消耗:38.1 MB,击败了90.03% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
【LeetCode】150. Evaluate Reverse Polish Notation 逆波兰表达式求值(Medium)(JAVA)
上一篇:排序-150-等差数列


下一篇:[leetCode]150. 逆波兰表达式求值