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.
思路:使用数据结构栈。碰到左操作符就进栈,右操作符就判断栈是否为空,空则return Fasle,不空则pop下是不是对应的左操作符,不是就return False。最后判断栈是否空,不空return False,否则return True.
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] lf = ['(','{','['] rt = [')', '}',']'] for i in s: if i in lf: stack.append(i) elif i in rt: ind = rt.index(i) if len(stack)==0 or stack.pop()!=lf[ind]:return False if len(stack)!=0 :return False return True
新闻热点
疑难解答