File tree 1 file changed +12
-20
lines changed
1 file changed +12
-20
lines changed Original file line number Diff line number Diff line change 18
18
def is_balanced (S ):
19
19
20
20
stack = []
21
-
21
+ open_brackets = set ({'(' , '[' , '{' })
22
+ closed_brackets = set ({')' , ']' , '}' })
23
+ open_to_closed = dict ({'{' :'}' , '[' :']' , '(' :')' })
24
+
22
25
for i in range (len (S )):
23
-
24
- if S [i ] == '(' or S [ i ] == '{' or S [ i ] == '[' :
26
+
27
+ if S [i ] in open_brackets :
25
28
stack .append (S [i ])
26
-
27
- else :
28
-
29
- if len (stack ) > 0 :
30
-
31
- pair = stack .pop () + S [i ]
32
-
33
- if pair != '[]' and pair != '()' and pair != '{}' :
34
- return False
35
-
36
- else :
29
+
30
+ elif S [i ] in closed_brackets :
31
+ if len (stack ) == 0 or (len (stack ) > 0 and open_to_closed [stack .pop ()] != S [i ]):
37
32
return False
38
-
39
- if len (stack ) == 0 :
40
- return True
41
-
42
- return False
33
+
34
+ return len (stack ) == 0
43
35
44
36
45
37
def main ():
@@ -48,7 +40,7 @@ def main():
48
40
49
41
if is_balanced (S ):
50
42
print (S , "is balanced" )
51
-
43
+
52
44
else :
53
45
print (S , "is not balanced" )
54
46
You can’t perform that action at this time.
0 commit comments