perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 316 - Task 2: Subsequence

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-316/#TASK2
 3 #
 4 # Task 2: Subsequence
 5 # ===================
 6 #
 7 # You are given two string.
 8 #
 9 # Write a script to find out if one string is a subsequence of another.
10 #
11 # A subsequence of a string is a new string that is formed from the original string
12 # by deleting some (can be none)  of the characters without disturbing the relative
13 # positions of the remaining characters.
14 #
15 #
16 ## Example 1
17 ##
18 ## Input: $str1 = "uvw", $str2 = "bcudvew"
19 ## Output: true
20 #
21 #
22 ## Example 2
23 ##
24 ## Input: $str1 = "aec", $str2 = "abcde"
25 ## Output: false
26 #
27 #
28 ## Example 3
29 ##
30 ## Input: $str1 = "sip", $str2 = "javascript"
31 ## Output: true
32 #
33 ############################################################
34 ##
35 ## discussion
36 ##
37 ############################################################
38 #
39 # We just split each string into an array for easier handling
40 # of the characters. Then we walk from left to right with two
41 # index variables. We search for an index in the second string
42 # where the character is the same as the character at the index
43 # in the first string. When the two characters match, we move both
44 # indices forward. If we reach the end of str2 before we reach the
45 # end of str1, we return false.
46 
47 use v5.36;
48 
49 subsequence("uvw", "bcudvew");
50 subsequence("aec", "abcde");
51 subsequence("sip", "javascript");
52 
53 sub subsequence($str1, $str2) {
54     say "Input: \"$str1\", \"$str2\"";
55     my @tmp1 = split //, $str1;
56     my @tmp2 = split //, $str2;
57     my ($i, $j) = (0, 0);
58     while($i <= $#tmp1) {
59         while($tmp1[$i] ne $tmp2[$j]) {
60             $j++;
61             return say "Output: false" if $j > $#tmp2;
62         }
63         $i++;
64         $j++;
65         return say "Output: false" if $j > $#tmp2 and $i <= $#tmp1;
66     }
67     say "Output: true";
68 }