NeetCode #368LC-3174EasyStack
← Back to All Problems#368 · #3174 · Clear Digits(清除数字)
📌 Problem Statement & Constraints
You are given a string
s. Repeatedly remove every digit and the closest non-digit character to its left, until no digits remain. Return the resulting string. Constraints: 1 <= s.length <= 100; the input guarantees the operation is always possible.💡 Core Algorithmic Approaches
- This is Removing Stars From a String with digits in place of stars.
- Push non-digit characters; on a digit, pop the top.
- The guarantee that the operation is always possible means the stack is never empty when a digit arrives.
- The result is the stack joined.
💻 Benchmark Python3 Implementation
class Solution:
def clearDigits(self, s: str) -> str:
st = []
for ch in s:
if ch.isdigit():
st.pop() # remove the closest non-digit to the left
else:
st.append(ch)
return "".join(st)⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each character is pushed or popped once.
💾 Space Complexity
O(n) for the stack.
⚠️ Interview Pitfalls & Follow-ups
- Using
ch in '0123456789':isdigit()is clearer and handles any digit-like character. - Forgetting that the digit itself is also removed: it is never pushed, so this is automatic.
- Scanning backwards: also valid, but the forward stack is the natural model.
- Assuming the stack cannot be empty: the problem guarantees safety, but a defensive check is cheap.