Skip to content

Commit a33faa0

Browse files
committed
feat: Add Valid Parentheses solution
1 parent 905a15a commit a33faa0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

โ€Žvalid-parentheses/thispath98.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution:
2+
def isValid(self, s: str) -> bool:
3+
"""
4+
Intuition:
5+
stack ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋‹ซํžˆ๋Š” ๊ด„ํ˜ธ๊ฐ€ ์˜ฌ ๊ฒฝ์šฐ
6+
stack์˜ ๋งˆ์ง€๋ง‰๊ณผ ์ผ์น˜ํ•˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.
7+
8+
Time Complexity:
9+
O(N):
10+
๋ฌธ์ž์—ด์„ ํ•œ๋ฒˆ ์Šค์บ”ํ•˜๋ฉด์„œ ์กฐ๊ฑด๋ฌธ์„ ํ™•์ธํ•˜๋ฏ€๋กœ
11+
O(N)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ์†Œ์š”๋œ๋‹ค.
12+
13+
Space Complexity:
14+
O(N):
15+
์ตœ์•…์˜ ๊ฒฝ์šฐ ๋ฌธ์ž์—ด ๊ฐœ์ˆ˜๋งŒํผ stack์— ์ €์žฅํ•œ๋‹ค.
16+
"""
17+
stack = []
18+
for ch in s:
19+
if ch in ["(", "{", "["]:
20+
stack.append(ch)
21+
elif ch in [")", "}", "]"]:
22+
if stack and (
23+
(ch == ")" and stack[-1] == "(")
24+
or (ch == "}" and stack[-1] == "{")
25+
or (ch == "]" and stack[-1] == "[")
26+
):
27+
stack.pop()
28+
else:
29+
return False
30+
31+
if stack:
32+
return False
33+
else:
34+
return True

0 commit comments

Comments
ย (0)