Skip to content

Commit 71aa2d0

Browse files
week 6: valid parentheses
1 parent c1cfd01 commit 71aa2d0

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
def isValid(self, s: str) -> bool:
3+
# time complexity: O(n)
4+
# space complexity: O(n)
5+
opens = ['(', '[', '{']
6+
closes = [')', ']', '}']
7+
required = []
8+
pair = {
9+
'(': ')',
10+
'[': ']',
11+
'{': '}'
12+
}
13+
answer = True
14+
for elem in s:
15+
if elem in opens:
16+
required.append(pair[elem])
17+
else:
18+
if elem in required and required[-1] == elem:
19+
required.pop()
20+
else:
21+
answer = False
22+
break
23+
return True if (answer and len(required) == 0) else False

0 commit comments

Comments
 (0)