-
Notifications
You must be signed in to change notification settings - Fork 0
/
q4_balanced.pl
75 lines (62 loc) · 2 KB
/
q4_balanced.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/perl
#
# Author : Harman Birdi
# Date : Sep 13, 2016
# Description : Program to determine if a string comprising of different kinds
# of brackets is balanced or not. The string is determined to be
# balanced if all sequences of brackets match adjacently or in
# a nested format. The brackets that can be used are '(', ')'
#
# Please note that brackets that are mix of adjacent and nested
# will NOT return as balanced like ()(())
#
# The solution does NOT make any difference from the previous one
# which had additional types of brackets. It works exactly as the
# last one though the code to check for additional types of
# brackets has been removed.
#
use strict;
use warnings FATAL => 'all';
#
# This subroutine checks if the brackets are balanced and returns 0 for FALSE
# else it returns 1 for TRUE.
#
sub balanced {
my @chars = split('', $_[0]); # Create queue of the string characters
my @stack = ();
# If length is odd, return 0
if (scalar(@chars) % 2 != 0) {
return 0;
}
# Check if brackets are balanced
for (my $i = 0; $i < scalar @chars; $i++) {
# If first character is from closing brackets, return 0
if (($i == 0) and ($chars[$i] eq ')')) {
return 0;
}
if (($chars[$i] eq '(')) {
push(@stack, $chars[$i]);
} else {
my $pop_char = pop(@stack);
if (($pop_char ne '(') and ($chars[$i] eq ')')) {
return 0;
}
}
}
# If stack is not empty after the loop completes, return 0
if (scalar @stack != 0) {
return 0;
}
return 1;
}
#
# Main starts here
#
my @arr = ('(())', '(()(', '()()()()', '()(())', '(', '');
foreach my $str (@arr) {
if (balanced($str)) {
print "String \'". $str ."\' is balanced.\n";
} else {
print "String \'". $str ."\' is NOT balanced.\n";
}
}