Skip to content

Commit 223a5c8

Browse files
committed
valid parenthese solution
1 parent 3e2c6d9 commit 223a5c8

File tree

1 file changed

+32
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)