perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 385 - Task 2: Outermost Parentheses

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-385/#TASK2
 3 #
 4 # Task 2: Outermost Parentheses
 5 # =============================
 6 #
 7 # You are given a valid parentheses string.
 8 #
 9 # Write a script to return the string after removing the outermost parentheses
10 # of every primitive string in the primitive decomposition of the given string.
11 #
12 ## Example 1
13 ##
14 ## Input: $str = "()()()"
15 ## Output: ""
16 ##
17 ## Primitive Decomposition: "()" + "()" + "()"
18 #
19 ## Example 2
20 ##
21 ## Input: $str = "(((())))"
22 ## Output: "((()))"
23 ##
24 ## Primitive Decomposition: "(((())))"
25 #
26 ## Example 3
27 ##
28 ## Input: $str = "(()())(())"
29 ## Output: "()()()"
30 ##
31 ## Primitive Decomposition: "(()())" + "(())"
32 #
33 ## Example 4
34 ##
35 ## Input: $str = "()((()))()"
36 ## Output: "(())"
37 ##
38 ## Primitive Decomposition: "()" + "((()))" + "()"
39 #
40 ## Example 5
41 ##
42 ## Input: $str = "(()(()))(()())"
43 ## Output: "()(())()()"
44 ##
45 ## Primitive Decomposition: "(()(()))" + "(()())"
46 #
47 ############################################################
48 ##
49 ## discussion
50 ##
51 ############################################################
52 #
53 # We walk $str character by character, keeping track of how deep we
54 # are into nested "()"s. We skip the opening "(" at level 0 and
55 # the closing ")" at level 1, but add all other "()"s to the
56 # output.
57 
58 use v5.36;
59 
60 outermost_parantheses("()()()");
61 outermost_parantheses("(((())))");
62 outermost_parantheses("(()())(())");
63 outermost_parantheses("()((()))()");
64 outermost_parantheses("(()(()))(()())");
65 
66 sub outermost_parantheses($str) {
67     say "Input: \"$str\"";
68     my $output = "";
69     my $level = 0;
70     foreach my $char (split //, $str) {
71         if($level == 0) {
72             if($char eq "(") {
73                 $level++;
74                 next;
75             }
76             # we shouldn't end up here as the input strings are valid
77         } elsif ($level == 1) {
78             if($char eq ")") {
79                 $level--;
80             } else {
81                 $level++;
82                 $output .= $char;
83             }
84             next;
85         }
86         $output .= $char;
87         if($char eq "(") {
88             $level++;
89         } else {
90             $level--;
91         }
92     }
93     say "Output: \"$output\"";
94 }