3174. Clear Digits
EasyView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Each digit character removes the closest non-digit to its left (if any).
Advertisement
Intuition
Each digit character removes the closest non-digit to its left (if any). Scan left to right with a stack: push non-digits, pop one character when you see a digit. Remaining stack is the answer — digits themselves are never kept.
Algorithm
- 1Stack<char> st.
- 2For each character c:
- 3If c is a digit and st not empty: pop once.
- 4Else if c is not a digit: push c.
- 5Return string built from stack.
Example Walkthrough
Input: s = "abc"
- 1.No digits — nothing removed. Output "abc".
Output: "abc"
Common Pitfalls
- •Digit triggers removal but is not added to result.
- •If stack empty on digit, skip removal.
- •Use char.IsDigit or compare to 0-9 range.
3174.cs
C#
// Approach: Stack; remove each digit and the nearest preceding non-digit character.
// Time: O(n) Space: O(n)
public class Solution
{
public string ClearDigits(string s)
{
StringBuilder sb = new StringBuilder();
foreach (char c in s)
{
if (char.IsDigit(c))
{
// Since `sb` only contains non-digit characters, popping the last
// character is equivalent to deleting the closest non-digit character.
if (sb.Length > 0)
sb.Length--;
}
else
sb.Append(c);
}
return sb.ToString();
}
}Advertisement
Was this solution helpful?