update project structure
This commit is contained in:
49
leetcode_py/20.py
Normal file
49
leetcode_py/20.py
Normal file
@@ -0,0 +1,49 @@
|
||||
# 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
|
||||
Reference in New Issue
Block a user