Valid Parentheses
LeetCode 20 · View on LeetCode
Push opening brackets onto a stack. For each closing bracket, check if it matches the top. Valid if the stack is empty at the end.
def is_valid(s: str) -> bool:
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for ch in s:
if ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
else:
stack.append(ch)
return not stack
if __name__ == '__main__':
print(is_valid("()")) # True
print(is_valid("()[]{}")) # True
print(is_valid("(]")) # False
print(is_valid("([)]")) # False
print(is_valid("{[]}")) # True