Table of Content
题目如下所示:
这道题用栈的思想比较好解,我稍微加强了下(如使用了将符号映射为数字),可提高算法的效率(提交时基本打败了100%)。我的参考代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ # s with odd length is not valid l = len(s) if l % 2 != 0: return False p = {"(": 1.1, ")": -1.1, "{": 2.22, "}": -2.22, "[": 3.333, "]": -3.333} num = [0] for c in s: if num[-1] + p[c] == 0: num.pop() else: num.append(p[c]) if len(num) != 1: return False else: return True |
另外看到一个很有意思的解法,非常简练(但结果看了效率不高),来自alessandrosolbiati:
1 2 3 4 5 6 7 |
def isValid(self, s): while '[]' in s or '()' in s or '{}' in s: s = s.replace('[]','').replace('()','').replace('{}','') return not len(s) |
如果您有好的建议,欢迎来信与我交流

也欢迎关注微信公众号“苔原带”
