LeetCode 150. Evaluate Reverse Polish Notation

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

题目

链接

https://leetcode.cn/problems/evaluate-reverse-polish-notation/

问题描述

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

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

注意 两个整数之间的除法只保留整数部分。

可以保证给定的逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

示例

输入:tokens = ["2","1","+","3","*"]
输出:9
解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9

提示

1 <= tokens.length <= 104
tokens[i] 是一个算符("+"、"-"、"*" 或 "/"),或是在范围 [-200, 200] 内的一个整数

思路

采用栈即可,进行处理,数字入栈,符号运算。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(n)

代码

Java

 public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String s : tokens) {
            if (s.equals("+")) {
                int b = stack.pop();
                int a = stack.pop();
                stack.push(a + b);
            } else if (s.equals("-")) {
                int b = stack.pop();
                int a = stack.pop();
                stack.push(a - b);
            } else if (s.equals("*")) {
                int b = stack.pop();
                int a = stack.pop();
                stack.push(a * b);
            } else if (s.equals("/")) {
                int b = stack.pop();
                int a = stack.pop();
                stack.push(a / b);
            } else {
                int num = Integer.parseInt(s);
                stack.push(num);
            }
        }
        return stack.pop();
    }
posted @ 2022-05-27 08:48  cheng102e  阅读(15)  评论(0编辑  收藏  举报