class Solution:
def isValid(self, s: str) -> bool:
stack = []
for c in s:
if c in ['(', '[', '{']:
stack.append(c)
else:
if not stack:
return False
if c == ')':
if stack.pop() != '(':
return False
elif c == ']':
if stack.pop() != '[':
return False
elif c == '}':
if stack.pop() != '{':
return False
if stack:
return False
return True
class Solution:
def isValid(self, s: str) -> bool:
stack = []
table = {')': '(', ']': '[', '}': '{'}
for c in s:
if c not in table:
stack.append(c)
elif not stack or stack.pop() != table[c]:
return False
return len(stack) == 0
dictionary로 짝을 맞추면 더 간결한 코드가 가능하다.
return len(stack) == 0
을 하면 굳이 첫 번째 제출처럼 if문을 쓰지 않아도 된다.
조금만 더 생각했으면 더 간결한 코드를 작성할 수 있었을 텐데 첫 번째 제출은 if문으로 하나하나 매칭해서 코드가 길어졌다.
그리고 return할 때 꼭 변수나 bool 아니더라도 return len(stack)==0
처럼 하면 더 간결하게 작성할 수 있다.