Skip to content

Instantly share code, notes, and snippets.

@huaxlin
Created January 7, 2023 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huaxlin/e1d8cb69b553d5fa48481c9bf1478951 to your computer and use it in GitHub Desktop.
Save huaxlin/e1d8cb69b553d5fa48481c9bf1478951 to your computer and use it in GitHub Desktop.
def is_balance(s) -> bool:
open, close = '<{[(', ')]}>'
brackets = dict(zip(open, close[::-1]))
# print( brackets )
stack = []
for c in s:
if c in brackets: # open; O(1)
stack.append(c) # .push
elif c in brackets.values(): # close; O(4)
if not stack: # .is_empty
return False
if c != brackets[stack[-1]]: # .peek
return False
stack.pop() # .pop
else: # support other string inside brackets
pass
return not stack
if __name__ == '__main__':
# is_balance(''); import sys; sys.exit(0)
assert is_balance('') is True
assert is_balance('()') is True
assert is_balance('[]') is True
assert is_balance('{}') is True
assert is_balance('<>') is True
assert is_balance('<{[()]}>') is True
assert is_balance('<>{[()]}') is True
assert is_balance('<>{[()]}<>') is True
assert is_balance('<{}>[()]') is True
assert is_balance('<{}>[(){[]}]') is True
for c in '<>{}[]()':
assert is_balance(c) is False
assert is_balance('[(]') is False
assert is_balance('{)}') is False
assert is_balance('{}(') is False
assert is_balance('{})') is False
assert is_balance('({}') is False
assert is_balance('){}') is False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment