1. 문제
https://leetcode.com/problems/valid-parentheses/
2. 접근 방법
stack의 기본 문제입니다요
주어진 문자열을 하나씩 확인해가면서 만약에 여는 괄호라면 stack에 담고,
닫는 괄호가 나올 경우 이와 쌍을 이루는 여는 괄호가 stack의 맨 뒤에 있다면 ok,
아니라면 false를 반환합니다.
문자열을 모두 순회한 후,
stack에 문자가 남아있다면 -> false
stack이 비었다면 -> true
3. 코드
python
class Solution:
def isValid(self, s: str) -> bool:
stack = []
table = {
')': '(',
'}': '{',
']': '['
}
for char in s:
if char not in table:
stack.append(char)
elif not stack or table[char] != stack.pop():
return False
return len(stack) == 0
4. 마치며
연결리스트만 하다가 스택으로 넘어오니까 편하네요 후 ~!
'Algorithm > Python' 카테고리의 다른 글
[LeetCode] 225. Implement Stack using Queues (0) | 2021.06.06 |
---|---|
[LeetCode] 739. Daily Temperatures (0) | 2021.06.06 |
[백준 2468] 안전영역 (0) | 2021.06.06 |
[백준 7569] 토마토 (0) | 2021.06.06 |
[백준 2644] 촌수계산 (0) | 2021.06.05 |