엔지니어 블로그
[Leetcode] 20. Valid Parentheses 본문
풀이
문제는 생각보다 간단하다. 다양한 종류의 괄호가 있고 이 괄호들이 문자열 s 안에 있을때 제대로 닫혀있는지 확인하면 되는 문제였다.
이전에 문제를 풀면서 너무 깊게 생각하면 자꾸 산으로 가는 경향이 있던 것을 떠올려 쉽게 쉽게 생각하기로 했다. 우선 각각의 괄호 값을 매핑한 dict를 생성한 후 s 의 값을 하나씩 list에 담아가면서 닫혀있는지 확인하는 식으로 진행하는 것으로 방향을 잡았다.
코드
class Solution:
def isValid(self, s: str) -> bool:
stack = []
str_dict = {'{':'}','[':']','(':')'}
for str in s:
if str in str_dict.values():
stack.append(str)
elif str in str_dict.keys():
if not stack or str_dict[str] != stack.pop():
return False
return not stack
'알고리즘' 카테고리의 다른 글
[Leetcode] 763. Partition Labels (0) | 2025.04.01 |
---|---|
[Leetcode] 49. Group Anagrams (0) | 2025.02.27 |
[Leetcode] 392.Is Subsequence (0) | 2025.02.12 |
[LeetCode] 1. Two Sum (0) | 2025.02.01 |
[Leetcode]2657. Find the Prefix Common Array of Two Arrays (0) | 2025.01.14 |