Dev102.com poses this programming challenge:
Your input is a string which is composed from bracket characters. The allowed characters are:'(', ')', '['. ']', '{', '}', '<' and '>'. Your mission is to determine whether the brackets structure is legal or not.
Example of a legal expression: "([](<{}>))".
Example of an illegal expression: "({<)>}".
Provide the most efficient, elegant and simple solution for that problem.
It's pretty obvious to me that you push opening brackets on the stack and pop off closing brackets, ensuring that the correct closing bracket is encountered. Like this:
def Evaluate(str):
stack = []
pushChars, popChars = "<({[", ">)}]"
for c in str :
if c in pushChars :
stack.append(c)
elif c in popChars :
if not len(stack) :
return False
else :
stackTop = stack.pop()
balancingBracket = pushChars[popChars.index(c)]
if stackTop != balancingBracket :
return False
else :
return False
return not len(stack)

Leave a comment