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.
思路:思路很简单,用stack保存当前最里面的左括号,一旦遇到匹配的右括号,就将其弹出,如果在遍历过程中,遇到右括号而且stack为空,则False, 遍历完成后如果stack不会空,则依然是False, 否则为True
class Solution:
# @return a boolean
def isValid(self, s):
stack = []
for par in s:
if par == '(' or par == '{' or par == '[':
stack.append(par)
elif len(stack) == 0:
return False
else:
tmp = stack.pop()
if tmp == '(':
if par != ')':
return False
elif tmp == '{':
if par != '}':
return False
else:
if par != ']':
return False
if len(stack) == 0:
return True
else:
return False