NeetCode #344LC-682EasyStackNC 250
← Back to All Problems#344 · #682 · Baseball Game(棒球比赛)
📌 Problem Statement & Constraints
You are keeping score for a baseball game with strange rules. Given a list of operations, return the total score. Operations: an integer
x records a new score; + records the sum of the previous two scores; D records double the previous score; C invalidates the previous score, removing it. Constraints: 1 <= operations.length <= 1000.💡 Core Algorithmic Approaches
- A stack of valid scores is the natural representation, since
Cremoves the most recent score and+/Ddepend on the most recent ones. +pushesstack[-1] + stack[-2];Dpushes2 * stack[-1];Cpops.- Integer operations push the parsed value.
- The answer is the sum of the stack at the end.
💻 Benchmark Python3 Implementation
class Solution:
def calPoints(self, operations: List[str]) -> int:
st = []
for op in operations:
if op == "+":
st.append(st[-1] + st[-2]) # sum of the last two
elif op == "D":
st.append(2 * st[-1]) # double the last
elif op == "C":
st.pop() # invalidate the last
else:
st.append(int(op))
return sum(st)⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each operation is O(1).
💾 Space Complexity
O(n) for the stack.
⚠️ Interview Pitfalls & Follow-ups
- Treating
DandCas numbers: they are operation codes, so the string comparison must come first. - Using
st[-2]without checking the length: the constraints guarantee validity, but defensive code would checklen(st) >= 2. - Modifying the list while iterating: the stack is separate from the operations list.
- Forgetting that
Cremoves rather than zeroes: the invalidated score must not contribute to later+orDoperations.
⚡
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
中文速览与面试要点
棒球比赛
你现在是一场采用特殊赛制棒球比赛的记录员。这场比赛由若干回合组成,过去几回合的得分可能会被用来计算后续回合的得分。比赛开始时,记录是空白的。给你一个字符串列表 ops,其中 ops[i] 是你需要记录的第 i 项操作,ops 遵循下述规则:整数 x 表示本回合新获得分数 x; + 表示本回合新获得的得分是前两次得分的总和; D 表示本回合新获得的得分是前一次得分的两倍; C 表示前一次得分无效,将其从记录中移除。请你返回记录中所有得分的总和。约束:1 ≤ ops.length ≤ 1000;ops[i] 为 C 、 D 、 + 或一个表示整数的字符串;对于操作 C ,题目数据保证记录中至少有一个元素;对于操作 D 和 + ,题目数据保证记录中至少有 2 个元素。
核心要点
- 栈模拟(标准解) :用栈保存有效得分。遇到数字则压栈; + 压入栈顶两元素之和; D 压入栈顶的两倍; C 弹出栈顶。
- 为什么用栈 :所有操作都只涉及「最近的记录」,栈天然契合。
- + 的实现细节 : stack[-1] + stack[-2] —— 注意顺序不影响加法结果,但语义上是「前两次得分之和」。
- 返回总和 : sum(stack) 。
常见陷阱
- C 操作时删除的是「所有记录」而非「前一次」 :题目说「前一次得分无效」,即只弹出一个。
- + 操作时先弹出再计算 :不能弹出, + 是「新增」一个得分,原有记录要保留。
- 忘记把数字字符串转 int : op 是字符串类型。
- 用列表的 pop(0) 模拟队首 :本题只涉及栈顶操作,用 pop() 即可。
参考实现
class Solution:
def calPoints(self, operations: list[str]) -> int:
stack = []
for op in operations:
if op == '+':
stack.append(stack[-1] + stack[-2]) # 前两次得分之和
elif op == 'D':
stack.append(stack[-1] * 2) # 前一次得分的两倍
elif op == 'C':
stack.pop() # 作废前一次得分
else:
stack.append(int(op))
return sum(stack)