perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 349 - Task 1: Power String

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-349/#TASK1
 3 #
 4 # Task 1: Power String
 5 # ====================
 6 #
 7 # You are given a string.
 8 #
 9 # Write a script to return the power of the given string.
10 #
11 ### The power of the string is the maximum length of a non-empty substring that
12 ### contains only one unique character.
13 #
14 ## Example 1
15 ##
16 ## Input: $str = "textbook"
17 ## Output: 2
18 ##
19 ## Breakdown: "t", "e", "x", "b", "oo", "k"
20 ## The longest substring with one unique character is "oo".
21 #
22 #
23 ## Example 2
24 ##
25 ## Input: $str = "aaaaa"
26 ## Output: 5
27 #
28 #
29 ## Example 3
30 ##
31 ## Input: $str = "hoorayyy"
32 ## Output: 3
33 ##
34 ## Breakdown: "h", "oo", "r", "a", "yyy"
35 ## The longest substring with one unique character is "yyy".
36 #
37 #
38 ## Example 4
39 ##
40 ## Input: $str = "x"
41 ## Output: 1
42 #
43 #
44 ## Example 5
45 ##
46 ## Input: $str = "aabcccddeeffffghijjk"
47 ## Output: 4
48 ##
49 ## Breakdown: "aa", "b", "ccc", "dd", "ee", "ffff", "g", "h", "i", "jj", "k"
50 ## The longest substring with one unique character is "ffff".
51 #
52 ############################################################
53 ##
54 ## discussion
55 ##
56 ############################################################
57 #
58 # We simply walk the characters, keeping track of the current streak of same
59 # characters. If we have a new maximum streak, we keep track of that as well.
60 # In the end, we have found the longest substring.
61 #
62 use v5.36;
63 
64 power_string("textbook");
65 power_string("aaaaa");
66 power_string("hoorayyy");
67 power_string("x");
68 power_string("aabcccddeeffffghijjk");
69 
70 sub power_string($str) {
71     say "Input: '$str'";
72     my @chars = split //,$str;
73     my ($prev, $len) = (undef, 0);
74     my $max = 0;
75     foreach my $char (@chars) {
76         if(!$prev or $char eq $prev) {
77             $prev = $char;
78             $len++;
79         } else {
80             $max = $len if $len > $max;
81             $prev = $char;
82             $len = 1;
83         }
84     }
85     $max = $len if $len > $max;
86     say "Output: $max";
87 }