Skip to content

3174. Clear Digits

Description

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.

 

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 <= 100
  • s consists only of lowercase English letters and digits.
  • The input is generated such that it is possible to delete all digits.

Solutions

Solution 1: Stack + Simulation

We use a stack stk to simulate this process. We traverse the string s. If the current character is a digit, we pop the top element from the stack. Otherwise, we push the current character into the stack.

Finally, we concatenate the elements in the stack into a string and return it.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string s.

1
2
3
4
5
6
7
8
9
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)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    public String clearDigits(String s) {
        StringBuilder stk = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                stk.deleteCharAt(stk.length() - 1);
            } else {
                stk.append(c);
            }
        }
        return stk.toString();
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
public:
    string clearDigits(string s) {
        string stk;
        for (char c : s) {
            if (isdigit(c)) {
                stk.pop_back();
            } else {
                stk.push_back(c);
            }
        }
        return stk;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func clearDigits(s string) string {
    stk := []byte{}
    for i := range s {
        if s[i] >= '0' && s[i] <= '9' {
            stk = stk[:len(stk)-1]
        } else {
            stk = append(stk, s[i])
        }
    }
    return string(stk)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function clearDigits(s: string): string {
    const stk: string[] = [];
    for (const c of s) {
        if (!isNaN(parseInt(c))) {
            stk.pop();
        } else {
            stk.push(c);
        }
    }
    return stk.join('');
}

Comments