Skip to content

Commit e3571de

Browse files
committed
valid-parentheses solution
1 parent d212055 commit e3571de

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution:
2+
def isValid(self, s: str) -> bool:
3+
'''
4+
๋ฌธ์ œ: string s ์— ๋Œ€ํ•ด์„œ valid parentheses ์ด๋ฉด true ์•„๋‹ˆ๋ฉด false
5+
conditions
6+
- open brackets must be closed by the same type
7+
- // must be closed in the correct order
8+
- s ์ตœ์†Œ ๊ธธ์ด = 1, ์ตœ๋Œ€ 10^4
9+
solution
10+
- open brackets -> st array ์— ์ €์žฅ, close brackets -> st.pop -> check valid
11+
- ๋งˆ์ง€๋ง‰์— st array length ๊ฐ€ 1 ์ด์ƒ์ด๋ฉด return False
12+
13+
- time complexity: O(n)
14+
- space complexity: O(n)
15+
'''
16+
17+
st = []
18+
19+
for i in range(len(s)):
20+
if s[i] == '(' or s[i] == '{' or s[i] == '[':
21+
st.append(s[i])
22+
else:
23+
# check if st is empty
24+
if len(st) <= 0:
25+
return False
26+
cur = st.pop()
27+
if s[i] == ')' and cur != '(':
28+
return False
29+
if s[i] == '}' and cur != '{':
30+
return False
31+
if s[i] == ']' and cur != '[':
32+
return False
33+
if len(st) > 0:
34+
return False
35+
return True
36+
37+

0 commit comments

Comments
ย (0)