Task 1: Last Word
"Finding the Final Frontier: Measuring the Last Word!"
Given a string, we need to return the length of the last word. A word is defined as a sequence of non-whitespace characters.
The Strategy: Both implementations use the built-in splitting mechanisms of the languages. In Python, split() automatically handles multiple spaces and trims the string. In Perl, a global regex match (\S+) captures all non-whitespace tokens, and we simply return the length of the last one.
sub last_word_length {
my ($str) = @_;
my @words = $str =~ /(\S+)/g;
return @words ? length( $words[-1] ) : 0;
}
def last_word_length(text: str) -> int:
words = text.split()
return len(words[-1]) if words else 0
Task 2: Buddy Strings
"String Symmetry: Can One Swap Make Them Equal?"
Two strings are "Buddy Strings" if exactly one pair of characters in one string can be swapped to make it identical to the other string.
The Strategy: First, ensure both strings have the same length. If the strings are already identical, they are buddies only if there's at least one repeating character (allowing a swap of identical characters). If the strings differ, they must have exactly two mismatched positions where the characters are cross-matches (e.g., source[i] == target[j] and source[j] == target[i]).
sub are_buddy_strings {
my ( $src, $tgt ) = @_;
return 0 if length($src) != length($tgt);
my @diff;
for my $idx ( 0 .. length($src) - 1 ) {
my $s_char = substr $src, $idx, 1;
my $t_char = substr $tgt, $idx, 1;
next if $s_char eq $t_char;
push @diff, [ $s_char, $t_char ];
return 0 if @diff > 2;
}
if ( @diff == 0 ) {
my %seen;
for my $char ( split //, $src ) {
return 1 if ++$seen{$char} > 1;
}
return 0;
}
return @diff == 2 && $diff[0][0] eq $diff[1][1] && $diff[0][1] eq $diff[1][0];
}
def are_buddy_strings(source: str, target: str) -> bool:
if len(source) != len(target):
return False
if source == target:
return len(set(source)) < len(source)
differences = [(s, t) for s, t in zip(source, target) if s != t]
if len(differences) != 2:
return False
(s1, t1), (s2, t2) = differences
return s1 == t2 and s2 == t1