Skip to content

Commit

Permalink
Merge pull request TheAlgorithms#180 from mathildapurr/fix_balanced_b…
Browse files Browse the repository at this point in the history
…rackets

fixed issue TheAlgorithms#171
  • Loading branch information
sachinarora707 authored Oct 24, 2017
2 parents 70c11da + b0d5301 commit b039fcb
Showing 1 changed file with 12 additions and 20 deletions.
32 changes: 12 additions & 20 deletions other/nested_brackets.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,28 +18,20 @@
def is_balanced(S):

stack = []

open_brackets = set({'(', '[', '{'})
closed_brackets = set({')', ']', '}'})
open_to_closed = dict({'{':'}', '[':']', '(':')'})

for i in range(len(S)):
if S[i] == '(' or S[i] == '{' or S[i] == '[':

if S[i] in open_brackets:
stack.append(S[i])

else:

if len(stack) > 0:

pair = stack.pop() + S[i]

if pair != '[]' and pair != '()' and pair != '{}':
return False

else:

elif S[i] in closed_brackets:
if len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != S[i]):
return False

if len(stack) == 0:
return True

return False

return len(stack) == 0


def main():
Expand All @@ -48,7 +40,7 @@ def main():

if is_balanced(S):
print(S, "is balanced")

else:
print(S, "is not balanced")

Expand Down

0 comments on commit b039fcb

Please sign in to comment.