[LeetCode] 20. Valid Parentheses
2021. 1. 18. 00:15ㆍProblem Solving/LeetCode
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
파이썬 알고리즘 인터뷰
|
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[Leetcode] 225. Implement Stack using Queues (0) | 2021.01.18 |
---|---|
[Leetcode] 739. Daily Temperatures (0) | 2021.01.18 |
[LeetCode] 328. Odd Even Linked List (0) | 2021.01.15 |
[LeeCode] 24. Swap Nodes in Pairs (0) | 2021.01.14 |
[LeetCode] 2. Add Two Numbers (0) | 2021.01.14 |