-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20.ValidParentheses.py
More file actions
39 lines (37 loc) · 1.08 KB
/
20.ValidParentheses.py
File metadata and controls
39 lines (37 loc) · 1.08 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
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
:note:
用list实现栈,但是list没有top方法,可以用pop和append代替
合法的字符串在栈里面最终都会被消掉,否则为非法字符串
"""
#s = "){"
stack = ['t']
stackI = 0
l = len(s)
ans = True
for i in range(l):
top = stack.pop()
if top == 't':
stack.append(top)
stack.append(s[i])
elif top in '({[':
if self.match(top, s[i]):
continue
else:
stack.append(top)
stack.append(s[i])
else:
ans = False
break
#print stack
if len(stack) > 1:
ans = False
return ans
def match(self, a, b):
if (a=='(' and b==')') or (a=='[' and b==']') or (a=='{' and b=='}'):
return True
else:
return False