-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20.py
More file actions
54 lines (47 loc) · 1.17 KB
/
20.py
File metadata and controls
54 lines (47 loc) · 1.17 KB
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
48
49
50
51
52
53
54
'''
20. Valid Parentheses
Given a string containing just the characters
'(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}"
are all valid but "(]" and "([)]" are not.
'''
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if s == "":
return True
if len(s) % 2 == 1:
return False
ret = []
ret.append(s[0])
for i in s[1:]:
if len(ret) == 0 or self.reverse(i) != ret[-1]:
ret.append(i)
else:
ret.pop()
if len(ret) == 0:
return True
else:
return False
def reverse(self, b):
if b == "(":
return ")"
elif b == ")":
return "("
elif b == "[":
return "]"
elif b == "]":
return "["
elif b == "{":
return "}"
elif b == "}":
return "{"
else:
return None
if __name__ == "__main__":
a = "({[]})"
sol = Solution()
print(sol.isValid(a))