题目:括号匹配问题
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.
解题:
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.
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
"""
根据tag给的提示,应该是用到了stack的思想
构建一个字典,将右括号放在keys,左括号放在values
如果s中的元素在values中,压栈append
如果在keys中:栈为空或没有匹配的左括号,false
其他情况false
最终栈应该是空的,都对应的pop掉了
"""
dict = {'}':'{',']':'[',')':'('}
stack = []
for ch in s:
if ch in dict.values():
stack.append(ch)
elif ch in dict.keys():
if stack == [] or dict[ch] != stack.pop():
return False
else:
return False
return stack == []