This was uqite straightforward as I used a stack to track and remove the characters. I then iterated through the string character by character. If the character was a digit, I removed the closest non-digit character to its left by popping the top element from the stack (if it wasn’t empty). If the character was not a digit, I simply added it to the stack.
At the end of the process, the stack contained only the remaining characters. I then joined them together to form the final result and returned it.
class Solution:
def clearDigits(self, s: str) -> str:
stack = []
for i in s:
if i.isdigit():
if stack:
stack.pop()
else:
stack.append(i)
return "".join(stack)
- Time: O(n)
- Space: O(n)
