题目:
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.
题解:
【字符串处理】
用一个List当作堆栈,遇到左括号压栈,遇到右括号弹栈比较。
最后check一下栈是否为空即可。
Code:
class Solution:
# @return a boolean
def isValid(self, s):
p = []
l = ['(','[','{']
r = [')',']','}']
for c in s:
if c in l:
p.append(c)
elif c in r:
if p == []:
return False
if p.pop() != l[r.index(c)]:
return False
if p == []:
return True
else:
return False