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. 解法: 利用栈做匹配,正括号都入栈,反括号入栈时查看有无匹配,有则对应正括号出栈,否则匹配失败,字符串不合法。当最终栈空时匹配成功,否则失败。特别注意“( [ ) ]”的情况,是不合法的。代码如下: 12345678910111213141516171819202122232425262728 class : def isValid(self, s): """ :type s: str :rtype: bool """ l = []; for c in s: if(c == '(' or c == '[' or c == '{'): l.append(c); elif(c == ')'): if(len(l) != 0 and l[-1] == '('): l = l[:-1]; else: return False; elif(c == ']'): if(len(l) != 0 and l[-1] == '['): l = l[:-1]; else: return False; elif(c == '}'): if(len(l) != 0 and l[-1] == '{'): l = l[:-1]; else: return False; if(len(l) == 0): return True; return False; 赞微海报分享
近期评论