-
[리트코드] (LeetCode) 20번 Valid Parentheses 문제Problem Solving/LeetCode 2021. 7. 5. 17:37
스택 자료구조를 활용한 대표적인 알고리즘 문제다.
괄호를 딕셔너리 형태로 짝을 지어주고,
for문에서 문자열에 닫는 괄호를 접근할때마다 pop을 해서 stack에 여는 괄호랑 비교하면서 풀었다
크게 어려울 것은 없었지만 예외처리에 신경써야 했다.
class Solution: def isValid(self, s: str) -> bool: stack = [] t = { ')': '(', '}': '{', ']': '[' } for c in s: if c not in t.values(): if len(stack) == 0: return False if stack.pop() != t[c]: return False else: stack.append(c) return False if len(stack) != 0 else True
'Problem Solving > LeetCode' 카테고리의 다른 글
[리트코드] (LeetCode) 24번 Swap Nodes in Pairs 문제 (0) 2021.07.05 [리트코드] (LeetCode) 21번 Merge Two Sorted Lists 문제 (0) 2021.07.05 [리트코드] (LeetCode) 15번 3Sum 문제 (0) 2021.07.05 [리트코드] (LeetCode) 2번 Add Two Numbers 문제 (0) 2021.07.05 [리트코드] (LeetCode) 1번 Two Sum 문제 (0) 2021.06.15