https://leetcode.com/problems/valid-parentheses/description/
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for c in s:
if c in ["(", "{", "["]:
stack.append(c)
else:
if len(stack) == 0:
return False
last = stack.pop()
if c == ")" and last != "(":
return False
elif c == "}" and last != "{":
return False
elif c == "]" and last != "[":
return False
return len(stack) == 0
class Solution:
def isValid(self, s: str) -> bool:
parentheses_table = {
")": "(",
"}": "{",
"]": "["
}
stack = []
for c in s:
if parentheses_table.get(c) is None:
stack.append(c)
print(stack)
elif not stack or parentheses_table.get(c) != stack.pop():
return False
return len(stack) == 0
dictionary를 이용하면 조금 더 깔끔한 코드가 작성 가능하다.
파이썬 알고리즘 인터뷰 20번