Leetcode(20) Valid Parentheses

Description:

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.

解法:

利用栈做匹配,正括号都入栈,反括号入栈时查看有无匹配,有则对应正括号出栈,否则匹配失败,字符串不合法。当最终栈空时匹配成功,否则失败。特别注意“( [ ) ]”的情况,是不合法的。代码如下:

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
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
l = [];
for c in s:
if(c == '(' or c == '[' or c == '{'):
l.append(c);
elif(c == ')'):
if(len(l) != 0 and l[-1] == '('):
l = l[:-1];
else:
return False;
elif(c == ']'):
if(len(l) != 0 and l[-1] == '['):
l = l[:-1];
else:
return False;
elif(c == '}'):
if(len(l) != 0 and l[-1] == '{'):
l = l[:-1];
else:
return False;
if(len(l) == 0):
return True;
return False;