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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。