Created
January 7, 2023 14:32
-
-
Save huaxlin/e1d8cb69b553d5fa48481c9bf1478951 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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