3174. Clear Digits

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.

Solution 1: Stack + Simulation


JAVA

  • 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();
        }
    }

C++

  • 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;
        }
    };

PYTHON

  • class Solution:
        def clearDigits(self, s: str) -> str:
            stk = []
            for c in s:
                if c.isdigit():
                    if stk:
                        stk.pop()
                else:
                    stk.append(c)
            return "".join(stk)

Comments