50 lines
1.1 KiB
Python

# give a string s containing just '(', ')' and else
# determine if the input is valid
class Solution:
def isValid(self, s: str) -> bool:
"""
# too slow
symbol_dict = {"(": ")", "{": "}", "[": "]"}
stack = []
for i in s:
try:
stack_top = stack.pop()
except IndexError:
stack.append(i)
continue
try:
if symbol_dict[stack_top] == i:
continue
stack.append(stack_top)
except KeyError:
return False
stack.append(i)
if stack:
return False
return True
"""
# Optimized solution
bracket_map = {")": "(", "}": "{", "]": "["}
stack = []
for char in s:
if char in bracket_map:
top_element = stack.pop() if stack else "#"
if bracket_map[char] != top_element:
return False
else:
stack.append(char)
return not stack