Created
October 29, 2017 10:40
-
-
Save hoanbka/1d4f5f6cc76b715888ccc1d12e3e7f2b to your computer and use it in GitHub Desktop.
check a balanced Parenthesis
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 isBalancedParenthesis(str): | |
stack = [] | |
for i in str: | |
if i == '(' or i == '{' or i == '[': | |
stack.append(i) | |
elif i == ')' or i == '}' or i == ']': | |
if len(stack) == 0: | |
return False | |
else: | |
if stack[-1] == '(' and i == ')' or stack[-1] == '{' and i == '}' or stack[-1] == '[' and i == ']': | |
stack.pop() | |
if len(stack) == 0: | |
return True | |
else: | |
return False | |
# TEST | |
str = '()(){}[{()}]' | |
str2 = '[(a+b)*c] - (d+c)*{b*9}' | |
print(isBalancedParenthesis(str)) | |
print(isBalancedParenthesis(str2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment