Skip to main content
Back to problems
#3174
Easy Algorithms

Clear digits

String Stack Simulation
82.7% acceptance
Feb 24, 2026
691
26
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn clear_digits(s: String) -> String {
    let mut stack: Vec<char> = Vec::new();
    for c in s.chars() {
      if c.is_ascii_digit() {
        stack.pop(); // remove closest non-digit character to the left
      } else {
        stack.push(c);
      }
    }
    stack.into_iter().collect()
  }
}