perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 328 - Task 2: Good String

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-328/#TASK2
 3 #
 4 # Task 2: Good String
 5 # ===================
 6 #
 7 # You are given a string made up of lower and upper case English letters only.
 8 #
 9 # Write a script to return the good string of the given string. A string is
10 # called good string if it doesn’t have two adjacent same characters, one in
11 # upper case and other is lower case.
12 #
13 ## Example 1
14 ##
15 ## Input: $str = "WeEeekly"
16 ## Output: "Weekly"
17 ##
18 ## We can remove either, "eE" or "Ee" to make it good.
19 #
20 #
21 ## Example 2
22 ##
23 ## Input: $str = "abBAdD"
24 ## Output: ""
25 ##
26 ## We remove "bB" first: "aAdD"
27 ## Then we remove "aA": "dD"
28 ## Finally remove "dD".
29 #
30 #
31 ## Example 3
32 ##
33 ## Input: $str = "abc"
34 ## Output: "abc"
35 #
36 ############################################################
37 ##
38 ## discussion
39 ##
40 ############################################################
41 #
42 # As long as we have two adjacent same characters, one in upper and
43 # one in lower case, we remove that part from the string. What remains
44 # in the end is the good string.
45 
46 use v5.36;
47 
48 good_string("WeEeekly");
49 good_string("abBAdD");
50 good_string("abc");
51 
52 sub good_string($str) {
53     say "Input: $str";
54     my $found = 1;
55     while($found) {
56         $found = 0;
57         foreach my $c ("a".."z") {
58             my $C = uc($c);
59             if($str =~ m/$c$C/) {
60                 $str =~ s/$c$C//;
61                 $found = 1;
62             }
63             if($str =~ m/$C$c/) {
64                 $str =~ s/$C$c//;
65                 $found = 1;
66             }
67         }
68     }
69     say "Output: $str";
70 }