Clear Digits Problem
#3174
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3174.
You are given a string s.
Your task is to remove all digits by doing this operation repeatedly:
- Delete the first digit and the closest non-digit character to its left.
Return the resulting string after removing all digits.
Note that the operation cannot be performed on a digit that does not have any non-digit character to its left.
Example 1:
Input: s = "abc"
Output: "abc"
Explanation:
There is no digit in the string.
Example 2:
Input: s = "cb34"
Output: ""
Explanation:
First, we apply the operation on s[2], and s becomes "c4".
Then we apply the operation on s[1], and s becomes "".
Constraints:
1 <= s.length <= 100sconsists only of lowercase English letters and digits.- The input is generated such that it is possible to delete all digits.
Solution
Approach: Stack
Walk through the string with a stack. A digit removes the top of the stack (the closest non-digit on its left); any other character is pushed. The stack holds the answer.
Complexity: time O(n), space O(n).
class Solution:
def clearDigits(self, s: str) -> str:
stk = []
for c in s:
if c.isdigit():
stk.pop()
else:
stk.append(c)
return "".join(stk)