Task 1: Power String
"How Long Is the Streak? Measuring Repeated Characters!"
This week's first task asks us to find the "power" of a string — the maximum length of a contiguous substring that consists of a single repeated character. For example, in "hoorayyy" the answer is 3 because "yyy" at the end is the longest run of identical characters.
The Strategy: Walk through the string character by character, tracking the current run length. When the current character matches the previous one, increment the counter. Otherwise reset it to 1. Keep the maximum value seen so far. This is a single-pass O(n) scan.
Perl Implementation
sub power_string ($text) {
($text) = $STR_CHECK->($text);
die 'Expected a non-empty string' if length $text == 0;
my $max_run = 0;
my $run_len = 0;
my $prev = undef;
for my $char ( split //, $text ) {
if ( defined $prev && $char eq $prev ) {
++$run_len;
}
else {
$prev = $char;
$run_len = 1;
}
$max_run = $run_len if $run_len > $max_run;
}
return $max_run;
}
Python Implementation
def power_string(text: str) -> int:
"""Return the maximum run length of a repeated character."""
if not text:
raise ValueError("Expected a non-empty string")
best = 0
current = 0
previous = ""
for char in text:
if char == previous:
current += 1
else:
previous = char
current = 1
if current > best:
best = current
return best