-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsolution.py
47 lines (45 loc) · 1.13 KB
/
solution.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
46
47
"""
91 / 91 test cases passed.
Runtime: 40 ms
Memory Usage: 15 MB
"""
class Solution:
def isValid(self, s: str) -> bool:
stk = []
for c in s:
if c in ['(', '{', '[']:
stk.append(c)
elif c == ')':
if stk and stk[-1] == '(':
stk.pop()
else:
return False
elif c == '}':
if stk and stk[-1] == '{':
stk.pop()
else:
return False
elif c == ']':
if stk and stk[-1] == '[':
stk.pop()
else:
return False
return len(stk) == 0
"""
91 / 91 test cases passed.
Runtime: 52 ms
Memory Usage: 15.1 MB
"""
class Solution2:
def isValid(self, s: str) -> bool:
dct = {')':'(', '}':'{', ']':'['}
stk = []
for c in s:
if stk and c in dct:
if stk[-1] == dct[c]:
stk.pop()
else:
return False
else:
stk.append(c)
return not stk