Skip to content

Commit b039fcb

Browse files
Merge pull request #180 from mathildapurr/fix_balanced_brackets
fixed issue #171
2 parents 70c11da + b0d5301 commit b039fcb

File tree

1 file changed

+12
-20
lines changed

1 file changed

+12
-20
lines changed

Diff for: other/nested_brackets.py

+12-20
Original file line numberDiff line numberDiff line change
@@ -18,28 +18,20 @@
1818
def is_balanced(S):
1919

2020
stack = []
21-
21+
open_brackets = set({'(', '[', '{'})
22+
closed_brackets = set({')', ']', '}'})
23+
open_to_closed = dict({'{':'}', '[':']', '(':')'})
24+
2225
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:
2528
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]):
3732
return False
38-
39-
if len(stack) == 0:
40-
return True
41-
42-
return False
33+
34+
return len(stack) == 0
4335

4436

4537
def main():
@@ -48,7 +40,7 @@ def main():
4840

4941
if is_balanced(S):
5042
print(S, "is balanced")
51-
43+
5244
else:
5345
print(S, "is not balanced")
5446

0 commit comments

Comments
 (0)