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.
思路:给定字符串,由3类括号组成,现在判断它是否有效,括号对应即为有效。
读取输入的字符串,如果是左括号就入栈,右括号就判断它是否和栈顶元素对应,如果不对应肯定是无效的,对应则让其对应的左括号出栈。最后判断栈是否为空,为空即为有效。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
temp = [] //栈
dict={')':'(','}':'{',']':'['} //用字典来表示对应关系
l=list(s)
lens=len(s)
//只有一个元素或者第一个元素就是右括号,肯定无效
if lens<=1 or l[0] in dict:
return False
//遍历列表
for i in range(0,lens):
//如果遇到右括号就看它和左括号是否对应 对应就出栈栈顶元素 否则返回False
if (l[i] in dict):
if len(temp)==0 or dict[l[i]]!= temp.pop():
return False
//遇到左括号直接入栈即可
else:
temp.append(l[i])
//遍历完看栈是否为空
if len(temp)==0:
return True
return False
遇到的问题
list[]
dict[] (是中括号不是小括号)
没有;只有: