Skip to content

Commit ded4f69

Browse files
committed
solve(w06): 20. Valid Parentheses
1 parent c1cb3e1 commit ded4f69

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

valid-parentheses/seungriyou.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# https://leetcode.com/problems/valid-parentheses/
2+
3+
class Solution:
4+
def isValid(self, s: str) -> bool:
5+
"""
6+
[Complexity]
7+
- TC: O(n)
8+
- SC: O(n)
9+
10+
[Approach]
11+
s를 순회하면서 다음을 stack에 수행한다.
12+
- 닫는 괄호: stack이 비어있거나, stack.top이 매칭이 안 된다면 빠르게 False 반환 (+ 매칭이 된다면 stack.pop())
13+
- 여는 괄호: stack에 추가
14+
이렇게 전체를 순회했을 때 stack이 비어있어야 valid parentheses이다.
15+
"""
16+
17+
matches = {
18+
")": "(",
19+
"}": "{",
20+
"]": "["
21+
}
22+
23+
stack = []
24+
25+
for p in s:
26+
# 닫는 괄호: (1) stack이 비어있거나 (2) stack의 top이 pair가 아니라면 False (+ pair라면 stack.pop())
27+
if p in matches:
28+
if not stack or stack.pop() != matches[p]:
29+
return False
30+
# 여는 괄호: stack에 추가
31+
else:
32+
stack.append(p)
33+
34+
# stack이 비어있어야 valid parentheses
35+
return not stack

0 commit comments

Comments
 (0)