Task 1: Replace All ?
"The Character Puzzle: Filling in the Blanks!"
Replace every '?' character with a lowercase letter such that no two adjacent characters are the same.
The Strategy: Iterate through the string character by character. When a '?' is found, check the characters immediately before and after it (if they exist). Pick the first letter from 'a' to 'z' that doesn't match either neighbor and use it to replace the '?'. This greedy approach ensures the constraint is satisfied with minimal overhead.
Perl Implementation
sub replace_question_marks {
my ($str) = @_;
my @chars = split //, $str;
my $len = @chars;
for my $i (0 .. $len - 1) {
next unless $chars[$i] eq '?';
my $prev = $i > 0 ? $chars[$i - 1] : '';
my $next = $i < $len - 1 ? $chars[$i + 1] : '';
for my $candidate ('a' .. 'z') {
next if $candidate eq $prev;
next if $candidate eq $next;
$chars[$i] = $candidate;
last;
}
}
return join '', @chars;
}
Python Implementation
def replace_question_marks(text: str) -> str:
chars = list(text)
for i, ch in enumerate(chars):
if ch != "?":
continue
prev_ch = chars[i - 1] if i > 0 else ""
next_ch = chars[i + 1] if i < len(chars) - 1 else ""
for cand in string.ascii_lowercase:
if cand != prev_ch and cand != next_ch:
chars[i] = cand
break
return "".join(chars)