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.
AC代码:
class Solution(object): def isValid(self, s): match = {'[': ']', '(': ')', '{': '}'} statck_list = [] for i in xrange(len(s)): if statck_list != [] and match.has_key(statck_list[-1]) and s[i] == match[statck_list[-1]]: statck_list = statck_list[:-1] else: statck_list.append(s[i]) return statck_list == []
直接按照题目要求,用一个临时列表存放没有匹配的元素,最后判断是否临时列表是否为空即可。