The weekly challenge 329 - Task 2: Nice String
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-329/#TASK2 3 # 4 # Task 2: Nice 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 longest substring of the give string which is 10 # nice. A string is nice if, for every letter of the alphabet that the string 11 # contains, it appears both in uppercase and lowercase. 12 # 13 ## Example 1 14 ## 15 ## Input: $str = "YaaAho" 16 ## Output: "aaA" 17 # 18 # 19 ## Example 2 20 ## 21 ## Input: $str = "cC" 22 ## Output: "cC" 23 # 24 # 25 ## Example 3 26 ## 27 ## Input: $str = "A" 28 ## Output: "" 29 ## 30 ## No nice string found. 31 # 32 ############################################################ 33 ## 34 ## discussion 35 ## 36 ############################################################ 37 # 38 # For each character in $str, we use the lowercase character of it 39 # as the key in a hash. There we keep track of each character that 40 # we have seen so far whether it was in lower, upper or both cases. 41 # In the end, we walk the characters from $str again and just keep 42 # the ones for which we have seen both the lower and upper case 43 # variant. 44 45 use v5.36; 46 47 nice_string("YaaAho"); 48 nice_string("cC"); 49 nice_string("A"); 50 51 sub nice_string($str) { 52 say "Input: \"$str\""; 53 my @chars = split //, $str; 54 my $seen = {}; 55 my $result = ""; 56 foreach my $char (@chars) { 57 if($char =~ m/[a-z]/) { 58 $seen->{$char}->{lc} = 1; 59 } else { 60 $seen->{lc($char)}->{uc} = 1; 61 } 62 } 63 foreach my $char (@chars) { 64 if($seen->{lc($char)}->{lc} && $seen->{lc($char)}->{uc}) { 65 $result .= $char; 66 } 67 } 68 say "Output: \"$result\""; 69 } 70