-
Notifications
You must be signed in to change notification settings - Fork 1
/
39.py
46 lines (36 loc) · 881 Bytes
/
39.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""
Time Complexity: O(n)
n: length of s
"""
class Solution:
def isValid(self, s: str) -> bool:
cnt = [0, 0, 0]
parentheses = {
'(': (0, 1),
')': (0, -1),
'{': (1, 1),
'}': (1, -1),
'[': (2, 1),
']': (2, -1)
}
pairs = {
')': '(',
']': '[',
'}': '{'
}
last = ""
for ch in s:
idx, scr = parentheses.get(ch)
cnt[idx] += scr
if cnt[idx] < 0:
return False
if ch in ('[', '{', '('):
last += ch
continue
if last != "" and pairs.get(ch) != last[-1]:
return False
last = last[:-1]
for v in cnt:
if v != 0:
return False
return True