Skip to content

Commit 0d3ac69

Browse files
authored
Merge pull request #1867 from jongwanra/main
[jongwanra] WEEK 06 solutions
2 parents f670e4a + b45e7f6 commit 0d3ac69

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

valid-parentheses/jongwanra.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
[Problem]
3+
https://leetcode.com/problems/valid-parentheses/
4+
5+
[Brainstorming]
6+
1. 여는 괄호가 나올 경우에 Stack에 Push한다.
7+
2. 닫는 괄호가 나왔을 경우에 Stack 가장 위에 여는 괄호와 일치 여부를 확인한다.
8+
9+
이렇게 했을 때, 시간 복잡도는 O(N)으로 예상한다. (여기서 N은 s.length)
10+
11+
[Complexity]
12+
Time: O(N), N = s.length
13+
Space: O(N), N = stack.length
14+
"""
15+
16+
class Solution:
17+
def isValid(self, s: str) -> bool:
18+
bracket_dict = {'(':')', '{':'}', '[':']'}
19+
stack = []
20+
for bracket in s:
21+
# 여는 괄호인 경우 Stack 추가
22+
if bracket in bracket_dict:
23+
stack.append(bracket)
24+
# 닫는 괄호인 경우
25+
else:
26+
if not stack:
27+
return False
28+
if bracket_dict[stack.pop()] != bracket:
29+
return False
30+
31+
return not stack
32+
33+
sol = Solution()
34+
35+
# Normal Case
36+
print(sol.isValid("()") == True)
37+
print(sol.isValid("()[]{}") == True)
38+
print(sol.isValid("(]") == False)
39+
print(sol.isValid("([])") == True)
40+
print(sol.isValid("([)]") == False)
41+
42+
# Edge Case
43+
print(sol.isValid("(") == False)
44+
print(sol.isValid("]") == False)
45+
46+

0 commit comments

Comments
 (0)