Skip to content

Commit bbf9378

Browse files
committed
Add solution of valid parenthese
1 parent 844d202 commit bbf9378

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

valid-parentheses/bhyun-kim.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
20. Valid Parentheses
3+
https://leetcode.com/problems/valid-parentheses/description/
4+
5+
Solution
6+
Uses a stack to check if the parentheses are valid.
7+
8+
1. Initialize an empty stack.
9+
2. Iterate through each character in the string.
10+
3. If the character is an opening parenthesis,
11+
push it to the stack.
12+
4. If the character is a closing parenthesis,
13+
pop the stack and check if the opening parenthesis matches.
14+
5. If the stack is empty, return True.
15+
6. Otherwise, return False.
16+
17+
Time complexity: O(n)
18+
Space complexity: O(n)
19+
"""
20+
21+
22+
class Solution:
23+
def isValid(self, s: str) -> bool:
24+
stack = ""
25+
opening = ["(", "[", "{"]
26+
closing = [")", "]", "}"]
27+
28+
for _s in s:
29+
if _s in opening:
30+
stack = _s + stack
31+
else:
32+
if stack:
33+
if opening[closing.index(_s)] == stack[0]:
34+
stack = stack[1:]
35+
else:
36+
return False
37+
else:
38+
return False
39+
40+
if len(stack) > 0:
41+
return False
42+
else:
43+
return True

0 commit comments

Comments
 (0)