NeetCode #371LC-227MediumStack
← Back to All Problems#371 · #227 · Basic Calculator II(基本计算器 II)
📌 Problem Statement & Constraints
Given a string
s representing an expression with non-negative integers and the operators +, -, *, /, evaluate it. Division truncates toward zero and there is no operator precedence to parse for parentheses. Constraints: 1 <= s.length <= 3 * 10^5; the expression is always valid.💡 Core Algorithmic Approaches
- Use a stack to handle precedence:
+and-push the signed number, while*and/combine immediately with the stack top. - Accumulate multi-digit numbers as they are scanned.
- Trigger the operator handling when a non-digit (other than a space) is seen, or at the last character -- otherwise the final number would never be applied.
- The answer is the sum of the stack.
💻 Benchmark Python3 Implementation
class Solution:
def calculate(self, s: str) -> int:
st = []
num = 0
op = "+" # pending operator
for i, ch in enumerate(s):
if ch.isdigit():
num = num * 10 + int(ch) # multi-digit numbers
if (not ch.isdigit() and ch != " ") or i == len(s) - 1:
if op == "+":
st.append(num)
elif op == "-":
st.append(-num)
elif op == "*":
st.append(st.pop() * num)
else:
st.append(int(st.pop() / num)) # truncate toward zero
num = 0
op = ch # remember the operator for the next number
return sum(st)⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass with O(1) work per character.
💾 Space Complexity
O(n) for the stack (one entry per additive term).
⚠️ Interview Pitfalls & Follow-ups
- Forgetting the
i == len(s) - 1condition: the last number would never be applied. - Using
//for division: Python floors toward negative infinity;int(a / b)truncates toward zero. - Trying to evaluate strictly left to right: precedence requires either a stack or a two-pass approach.
- Not skipping spaces: they appear throughout the expression.
- Overwriting
opwith a space: the operator update must only happen on actual operators, which the condition handles.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Stack Problems
中文速览与面试要点
基本计算器 II
给你一个字符串表达式 s,请你实现一个基本计算器来计算并返回它的值。整数除法仅保留整数部分。你可以假设给定的表达式总是有效的。所有中间结果将在 [−2^31, 2^31 − 1] 的范围内。注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 eval() 。约束:1 ≤ s.length ≤ 3 × 10^5;s 由整数和算符 + 、 - 、 * 、 / 组成,中间由一些空格隔开;s 表示一个 有效表达式 ;表达式中的所有整数都是非负整数,且在范围 [0, 2^31 − 1] 内;题目数据保证答案是一个 32 位整数。
核心要点
- 栈处理优先级(标准解) :遍历字符串,用一个变量 num 累积当前数字、 op 记录上一个运算符。
- 遇到运算符时结算前一项 : + 压入 num ; - 压入 -num ; * 与 / 则 就地与栈顶运算 (弹出栈顶、计算后压回),这样高优先级运算被立即处理。
- 为什么乘法/除法要就地运算 :它们优先级高于加减,因此必须先把它们算完,最终栈中只剩下「待相加的项」, sum(stack) 即为答案。
- 遍历结束后别忘了结算最后一个数字 :循环内只在遇到运算符时结算,末尾的数字需要单独处理(可在字符串末尾追加一个 + 简化)。
常见陷阱
- 忘记结算最后一个数字 :如 "3+2" 遍历到末尾时 num = 2 尚未入栈,必须补一次结算。
- 除法用 // :Python 的 // 向下取整, -7 // 2 = -4 ,题目要求向零截断。必须用 int(a / b) 。
- 乘法/除法用 stack.append(...) 而非就地运算 : * 和 / 必须与栈顶 就地 运算(先 pop 再 push 结果),不能新增一项。
- 用 eval() :题目明确禁止。
- 处理多位数时忘记 num = num * 10 + int(c) :只取一位会解析错误。
- 空格处理 :必须跳过空格,但空格不应触发结算。
参考实现
class Solution:
def calculate(self, s: str) -> int:
stack = []
num = 0
op = '+' # 记录上一个运算符
for i, c in enumerate(s):
if c.isdigit():
num = num * 10 + int(c)
elif c != ' ':
if op == '+':
stack.append(num)
elif op == '-':
stack.append(-num)
elif op == '*':
stack.append(stack.pop() * num)
else: # '/'
stack.append(int(stack.pop() / num)) # 向零截断
num = 0
op = c
# 结算最后一个数字(可视为末尾隐含一个 '+')
if op == '+':
stack.append(num)
elif op == '-':
stack.append(-num)
elif op == '*':
stack.append(stack.pop() * num)
else:
stack.append(int(stack.pop() / num))
return sum(stack)