[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.
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
逆波兰表达式,所有操作符置于操作数的后面,因此也被称为后缀表示法。逆波兰记法不需要括号来标识操作符的优先级。
逆波兰记法中,操作符置于操作数的后面。例如表达“三加四”时,写作“3 4 +”,而不是“3 + 4”。如果有多个操作符,操作符置于第二个操作数的后面,所以常规中缀记法的“3 - 4 + 5”在逆波兰记法中写作“3 4 - 5 +”:先3减去4,再加上5。使用逆波兰记法的一个好处是不需要使用括号。例如中缀记法中“3 - 4 * 5”与“(3 - 4)*5”不相同,但后缀记法中前者写做“3 4 5 * -”,无歧义地表示“3 (4 5 *) -”;后者写做“3 4 - 5 *”。
逆波兰表达式的解释器一般是基于堆栈的。解释过程一般是:操作数入栈;遇到操作符时,操作数出栈,求值,将结果入栈;当一遍后,栈顶就是表达式的值。因此逆波兰表达式的求值使用堆栈结构很容易实现,并且能很快求值。
注意:逆波兰记法并不是简单的波兰表达式的反转。因为对于不满足交换律的操作符,它的操作数写法仍然是常规顺序,如,波兰记法“/ 6 3”的逆波兰记法是“6 3 /”而不是“3 6 /”;数字的数位写法也是常规顺序。
解法1: 栈Stack
解法2: 递归
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class Solution { public int evalRPN(String[] tokens) { int a,b; Stack<Integer> S = new Stack<Integer>(); for (String s : tokens) { if (s.equals( "+" )) { S.add(S.pop()+S.pop()); } else if (s.equals( "/" )) { b = S.pop(); a = S.pop(); S.add(a / b); } else if (s.equals( "*" )) { S.add(S.pop() * S.pop()); } else if (s.equals( "-" )) { b = S.pop(); a = S.pop(); S.add(a - b); } else { S.add(Integer.parseInt(s)); } } return S.pop(); } } |
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public int evalRPN(String[] a) { Stack<Integer> stack = new Stack<Integer>(); for ( int i = 0 ; i < a.length; i++) { switch (a[i]) { case "+" : stack.push(stack.pop() + stack.pop()); break ; case "-" : stack.push(-stack.pop() + stack.pop()); break ; case "*" : stack.push(stack.pop() * stack.pop()); break ; case "/" : int n1 = stack.pop(), n2 = stack.pop(); stack.push(n2 / n1); break ; default : stack.push(Integer.parseInt(a[i])); } } return stack.pop(); } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # Time: O(n) # Space: O(n) import operator class Solution: # @param tokens, a list of string # @return an integer def evalRPN( self , tokens): numerals, operators = [], { "+" : operator.add, "-" : operator.sub, "*" : operator.mul, "/" : operator.div} for token in tokens: if token not in operators: numerals.append( int (token)) else : y, x = numerals.pop(), numerals.pop() numerals.append( int (operators[token](x * 1.0 , y))) return numerals.pop() if __name__ = = "__main__" : print (Solution().evalRPN([ "2" , "1" , "+" , "3" , "*" ])) print (Solution().evalRPN([ "4" , "13" , "5" , "/" , "+" ])) print (Solution().evalRPN([ "10" , "6" , "9" , "3" , "+" , "-11" , "*" , "/" , "*" , "17" , "+" , "5" , "+" ])) |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution { public : int evalRPN(vector<string> &tokens) { if (tokens.size() == 1) return atoi (tokens[0].c_str()); stack< int > s; for ( int i = 0; i < tokens.size(); ++i) { if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/" ) { s.push( atoi (tokens[i].c_str())); } else { int m = s.top(); s.pop(); int n = s.top(); s.pop(); if (tokens[i] == "+" ) s.push(n + m); if (tokens[i] == "-" ) s.push(n - m); if (tokens[i] == "*" ) s.push(n * m); if (tokens[i] == "/" ) s.push(n / m); } } return s.top(); } }; |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Solution { public : int evalRPN(vector<string>& tokens) { int op = tokens.size() - 1; return helper(tokens, op); } int helper(vector<string>& tokens, int & op) { string s = tokens[op]; if (s == "+" || s == "-" || s == "*" || s == "/" ) { int v2 = helper(tokens, --op); int v1 = helper(tokens, --op); if (s == "+" ) return v1 + v2; else if (s == "-" ) return v1 - v2; else if (s == "*" ) return v1 * v2; else return v1 / v2; } else { return stoi(s); } } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构