Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 백준 2504번
- 이분 그래프(Bipartite Graph)
- DFS
- 백준 1948번
- BFS(Breadth First Search)
- 그래프(Graph)
- 백준 2812번
- 동적 프로그래밍(Dynamic Programming)
- DFS & BFS
- BFS
- 스택(Stack)
- 이분 탐색(Binary Search)
- 백준 1707번
- 백준 2261번
- 백준 2493번
- 백준 18352번
- DFS(Depth First Search)
- 분할 정복(Divide and Conquer)
- 백준 10000번
- 알고리즘 개념
- 백준 21606번
- 다익스트라 알고리즘(Dijkstra Algorithm)
- 위상 정렬(Topology Sort)
- 백준 9012번
- 트리(Tree)
- 큐(Queue)
- 위상 정렬(Topological Sort)
- 플로이드 워셜 알고리즘(Floyd-Warshall Algorithm)
- 백준 17608번
- 그리디 알고리즘(Greedy Algorithm)
Archives
- Today
- Total
Always Be Wise
스택 : 유효한 괄호(리트코드 20번) 본문
728x90
▶ 문제 : https://leetcode.com/problems/valid-parentheses/
Valid Parentheses - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
##### 문제 #####
# 괄호로 된 입력값이 올바른지 판별하라.
##### 입력 #####
# ( ) [ ] { }
##### 출력 #####
# True
▶ 접근 방법
전형적인 스택 문제이다.
괄호 ( , [ , { 는 스택에 push하고 ), ] , } 는 스택에서 pop을 진행한다.
해당 과정에서 짝이 안맞거나, 스택에 남아 있는 것이 있다면 유효한 괄호가 아니다.
▶ 풀이 코드
def is_valid(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
s = "()[]{}"
print(is_valid(s))
'알고리즘 > 리트코드' 카테고리의 다른 글
스택 : 일일 온도(리트코드 739번) (0) | 2022.02.02 |
---|---|
스택 : 중복 문자 제거(리트코드 316번) (0) | 2022.02.02 |
배열 : 주식을 사고 팔기 가장 좋은 시점(리트코드 121번) (0) | 2022.01.31 |
배열 : 세 수의 합(리트코드 15번) (0) | 2022.01.30 |
배열 : 빗물 트래핑(리트코드 42번) (0) | 2021.12.15 |
Comments