Problem Solving/LeetCode
[LeetCode] 20. Valid Parentheses
yuseon-Lim
2021. 1. 18. 00:15
LeetCode 20. Valid Parentheses
Solution
class Solution:
def isValid(self, s: str) -> bool:
stack = []
bracket = {
')': '(',
']': '[',
'}': '{'
}
for char in s:
if char not in bracket:
stack.append(char) # open bracket
elif not stack or bracket[char] != stack.pop():
return False
return len(stack) == 0
- 괄호 짝 딕셔너리로 설정
- open bracket일경우 stack에 push
- open이 없거나, 짝이 안맞을 경우 return False
- stack에 남아있을 경우(open이 더 많음) return False
Reference
파이썬 알고리즘 인터뷰
![]() |
|
반응형