perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 321 - Task 2: Backspace Compare

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-321/#TASK2
 3 #
 4 # Task 2: Backspace Compare
 5 # =========================
 6 #
 7 # You are given two strings containing zero or more #.
 8 #
 9 # Write a script to return true if the two given strings are same by treating #
10 # as backspace.
11 #
12 ## Example 1
13 ##
14 ## Input: $str1 = "ab#c"
15 ##        $str2 = "ad#c"
16 ## Output: true
17 ##
18 ## For first string,  we remove "b" as it is followed by "#".
19 ## For second string, we remove "d" as it is followed by "#".
20 ## In the end both strings became the same.
21 #
22 #
23 ## Example 2
24 ##
25 ## Input: $str1 = "ab##"
26 ##        $str2 = "a#b#"
27 ## Output: true
28 #
29 #
30 ## Example 3
31 ##
32 ## Input: $str1 = "a#b"
33 ##        $str2 = "c"
34 ## Output: false
35 #
36 ############################################################
37 ##
38 ## discussion
39 ##
40 ############################################################
41 #
42 # As long as there's a # in the word following another character, we replce
43 # both the # character and the character before it. Once done on both characters,
44 # a simple string comparison shows whether the two strings are equal.
45 
46 use v5.36;
47 
48 backspace_compare( "ab#c", "ad#c" );
49 backspace_compare( "ab##", "a#b#" );
50 backspace_compare( "a#b", "c");
51 
52 +-- 14 lines: sub backspace_compare($str1, $str2) {---------------------------------------------------------------------------------------------------------------------------------