Skip to content

3174. Clear Digits 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  string clearDigits(string s) {
    string ans;

    for (const char c : s)
      if (isdigit(c))
        // Since `ans` only contains non-digit characters, popping the last
        // character is equivalent to deleting the closest non-digit character.
        ans.pop_back();
      else
        ans += c;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public String clearDigits(String s) {
    StringBuilder sb = new StringBuilder();

    for (final char c : s.toCharArray())
      if (Character.isDigit(c))
        // Since `sb` only contains non-digit characters, popping the last
        // character is equivalent to deleting the closest non-digit character.
        sb.setLength(sb.length() - 1);
      else
        sb.append(c);

    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def clearDigits(self, s: str) -> str:
    ans = []

    for c in s:
      if c.isdigit():
        # Since `ans` only contains non-digit characters, removing the last
        # character is equivalent to deleting the closest non-digit character.
        ans.pop()
      else:
        ans.append(c)

    return ''.join(ans)