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
新聞熱點
疑難解答