Task 1: Clear Digits
"The Digit Eraser: Cleaning Up Strings!"
Given a string of lowercase letters and digits, for every digit encountered, remove both the digit and the closest non-digit character to its left.
The Strategy: A stack-based approach is ideal here. We iterate through the string character by character. If the character is a digit, we pop the top element from the stack (the nearest non-digit to the left). If it's a letter, we push it onto the stack. At the end, the stack contains only the remaining letters.
Perl Implementation
sub clear_digits {
my ($str) = @_;
my @stack;
for my $ch (split //, $str) {
if ($ch =~ /\d/) {
pop @stack if @stack;
} else {
push @stack, $ch;
}
}
return join '', @stack;
}
Python Implementation
def clear_digits(text: str) -> str:
stack = []
for ch in text:
if ch.isdigit():
if stack:
stack.pop()
else:
stack.append(ch)
return "".join(stack)