150强访谈简单

评估逆波兰表示法

“评估逆波兰表示法”问题的详细指南和 Python 实现。

问题陈述

简单

给您一个字符串数组 tokens ,它表示逆波兰表示法中的算术表达式。

计算表达式并返回表示表达式值的整数。

请注意:

- 有效的运算符为“+”、“-”、“*”和“/”。

- 每个操作数可以是整数或另一个表达式。

- 两个整数之间的除法总是截断为零。

- 不会有任何被零除的情况。

- 输入表示采用逆波兰表示法的有效算术表达式。

编写一个函数 evalRPN(tokens: List[str]) -> int

约束条件
  • 1 <= len(tokens) <= 10^4
  • tokens[i] is either an operator (+, -, *, /) or an integer in the range [-200, 200]

示例

Example 1
Input
tokens = ["2", "1", "+", "3", "*"]
Output
9
Explanation

((2 + 1) * 3) = 9.

Example 2
Input
tokens = ["4", "13", "5", "/", "+"]
Output
6
Explanation

(4 + (13 / 5)) = (4 + 2) = 6. Note 13/5 truncates to 2.

Example 3
Input
tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output
22
Explanation

((10 * (6 / ((9 + 3) * -11))) + 17 + 5) = 22.

Need a Hint?
考虑使用特定于堆栈的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。