Skip to content

Commit 59433dd

Browse files
committed
isValid - AC but not a good solution
1 parent 622de8e commit 59433dd

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

leecode/有效的括号/isValid.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/python3
2+
# -*- coding: utf-8 -*-
3+
'''
4+
AC but not a good solution
5+
'''
6+
import time
7+
8+
9+
class Solution:
10+
def isValid(self, s):
11+
"""
12+
:type s: str
13+
:rtype: bool
14+
"""
15+
trantab = s.maketrans("()[]{}", "142536")
16+
s = s.translate(trantab)
17+
s = list(map(int, s))
18+
stack = []
19+
for i in s:
20+
if i < 4:
21+
stack.append(i)
22+
else:
23+
try:
24+
if i - stack.pop() == 3:
25+
pass
26+
else:
27+
return False
28+
except IndexError:
29+
return False
30+
else:
31+
return len(stack)==0
32+
33+
34+
if __name__ == "__main__":
35+
36+
t0 = time.perf_counter()
37+
testlist = ["(", "()[]{}", "(]", "([)]", "{[]}"]
38+
test = Solution()
39+
for i in testlist:
40+
print(test.isValid(i))
41+
42+
print(time.perf_counter() - t0)
43+
44+
'''
45+
class Solution:
46+
def isValid(self, s):
47+
"""
48+
:type s: str
49+
:rtype: bool
50+
"""
51+
stack = []
52+
for c in s:
53+
if c in ["{", "(", "["]:
54+
stack.append(c)
55+
else:
56+
if len(stack) == 0:
57+
return False
58+
currBracket = stack[-1] + c
59+
if currBracket not in ["{}", "[]", "()"]:
60+
return False
61+
stack.pop()
62+
return len(stack) == 0
63+
'''

0 commit comments

Comments
 (0)