3174. Clear Digits
EasyView on LeetCode
Time: O(n)
Space: O(n)
Advertisement
Intuition
Clear digits: each digit removes the first non-digit to its left. Stack simulation.
Algorithm
- 1Stack. For each char: if digit, pop top (if non-empty). Else push char.
Common Pitfalls
- •Digit removes nearest non-digit to its left. Stack handles LIFO order naturally.
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?