Skip to content

Commit c1627a0

Browse files
committed
add isValid function to validate parentheses using a stack
1 parent e34f9af commit c1627a0

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
# Approach
3+
์Šคํƒ์„ ์ด์šฉํ•˜์—ฌ ๋‹ซ๋Š” ๊ด„ํ˜ธ๊ฐ€ ๋‚˜์˜ฌ ๋•Œ ์Šคํƒ top๊ณผ ๋น„๊ตํ•˜์—ฌ ์ง์ด ๋งž์œผ๋ฉด popํ•ฉ๋‹ˆ๋‹ค.
4+
์ง์ด ๋งž์ง€ ์•Š์œผ๋ฉด invalid, ์ตœ์ข…์ ์œผ๋กœ ์Šคํƒ์ด ๋น„์–ด์žˆ์ง€ ์•Š์œผ๋ฉด invalid ํ•ฉ๋‹ˆ๋‹ค.
5+
6+
# Complexity
7+
s์˜ ๊ธธ์ด๋ฅผ N์ด๋ผ๊ณ  ํ•  ๋•Œ
8+
- Time complexity: O(N)
9+
- Space complexity: O(N)
10+
"""
11+
12+
13+
class Solution:
14+
def isValid(self, s: str) -> bool:
15+
stack = []
16+
brackets = {"(": ")", "{": "}", "[": "]"}
17+
for b in s:
18+
if b in brackets:
19+
stack.append(b)
20+
continue
21+
if not stack or brackets[stack.pop()] != b:
22+
return False
23+
if not stack:
24+
return True
25+
return False

0 commit comments

Comments
ย (0)