The Weekly Challenge 330

Clearing Digits & Capitalising Titles!

Original Challenge Link

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)

Task 2: Title Capital

"Style Guide: Perfecting Your Title Casing!"

Format a title string such that words of length 1 or 2 are entirely lowercase, and words of length 3 or more are capitalised.

The Strategy: Split the string into words using space as a delimiter. For each word, check its length. If the length is less than or equal to 2, lowercase the whole word. Otherwise, lowercase the whole word and then uppercase the first letter (capitalize). Finally, join the words back together with single spaces.
Perl Implementation
sub title_capital {
    my ($title) = @_;
    my @words = split / /, $title;
    @words = map {
        length($_) <= 2 ? lc $_ : ucfirst lc $_
    } @words;
    return join ' ', @words;
}
Python Implementation
def title_capital(title: str) -> str:
    words = title.split(" ")
    transformed = [
        word.lower() if len(word) <= 2 else word.capitalize()
        for word in words
    ]
    return " ".join(transformed)