Skip to content

Commit a177532

Browse files
committed
isValid - AC
1 parent 59433dd commit a177532

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed

leecode/有效的括号/isValid.py

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/python3
22
# -*- coding: utf-8 -*-
33
'''
4-
AC but not a good solution
4+
AC
55
'''
66
import time
77

@@ -12,23 +12,18 @@ def isValid(self, s):
1212
:type s: str
1313
:rtype: bool
1414
"""
15-
trantab = s.maketrans("()[]{}", "142536")
16-
s = s.translate(trantab)
17-
s = list(map(int, s))
18-
stack = []
15+
left = {'[': 1, '(':2, '{':3}
16+
right = {']':1, ')':2, '}':3}
17+
left_s = []
1918
for i in s:
20-
if i < 4:
21-
stack.append(i)
19+
if i in left:
20+
left_s.append(left[i])
2221
else:
23-
try:
24-
if i - stack.pop() == 3:
25-
pass
26-
else:
27-
return False
28-
except IndexError:
22+
if len(left_s) == 0:
23+
return False
24+
if left_s.pop() != right[i]:
2925
return False
30-
else:
31-
return len(stack)==0
26+
return len(left_s) == 0
3227

3328

3429
if __name__ == "__main__":
@@ -60,4 +55,6 @@ def isValid(self, s):
6055
return False
6156
stack.pop()
6257
return len(stack) == 0
58+
59+
6360
'''

0 commit comments

Comments
 (0)