Here is a classic brackets parsing problem. In this case we treat []{}()<> are treated as opening and closing brackets accordingly. Now the idea is to insert any bracket into a stack and pop it when we parse a closing bracket and then check whether the popped character is a corresponding opening bracket.
Here is the implementation below :
This file contains 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 checkBrackets(str): | |
list = [] | |
for c in str: | |
if c in "<([{": | |
list.append(c) | |
if c in ">)]}": | |
if len(list) == 0: | |
return 0 | |
popped = list.pop() | |
if c == ">": | |
if popped != "<": | |
return 0 | |
if c == ")": | |
if popped != "(": | |
return 0 | |
if c == "]": | |
if popped != "[": | |
return 0 | |
if c == "}": | |
if popped != "{": | |
return 0 | |
print list | |
if len(list)==0: | |
return 1 | |
else: | |
return 0 | |
print checkBrackets(")") |