20. Valid Parentheses
Given a string containing just '()[]{}', determine if the brackets are matched and properly nested.
def is_valid(s):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stack
Every opening bracket gets pushed. Every closing bracket must match whatever is currently on top of the stack -- if it doesn't, or the stack is empty, the string is invalid. A clean stack at the end means everything closed.