update 20

This commit is contained in:
sangge-rockpi 2024-01-20 18:19:37 +08:00
parent a4e2623dbf
commit 579e90ba94

View File

@ -4,6 +4,8 @@
class Solution:
def isValid(self, s: str) -> bool:
"""
# too slow
symbol_dict = {"(": ")", "{": "}", "[": "]"}
stack = []
for i in s:
@ -16,8 +18,8 @@ class Solution:
try:
if symbol_dict[stack_top] == i:
continue
else:
stack.append(stack_top)
stack.append(stack_top)
except KeyError:
return False
@ -28,3 +30,20 @@ class Solution:
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