题目如下所示:
这道题用栈的思想比较好解,我稍微加强了下(如使用了将符号映射为数字),可提高算法的效率(提交时基本打败了100%)。我的参考代码如下:
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:
def isValid(self, s):
while '[]' in s or '()' in s or '{}' in s:
s = s.replace('[]','').replace('()','').replace('{}','')
return not len(s)
ps:如果您有好的建议,欢迎交流 :-D,也欢迎访问我的个人博客:tundrazone.com