2024-01-20 13:48:01 +08:00

31 lines
694 B
Python

# give a string s containing just '(', ')' and else
# determine if the input is valid
class Solution:
def isValid(self, s: str) -> bool:
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
else:
stack.append(stack_top)
except KeyError:
return False
stack.append(i)
if stack:
return False
return True