1. 读懂题目
2. 分析,推导解法,产生思路。
解题思路:
(1)利用dict字典映射字符括号;list列表实现栈。 # 特殊处理:若字符串长度为奇数,则false;空字符串:ture
(2)取巧的方式:反复去掉配对的括号,直到没有可去除的括号为止。
(3)查看ASCII可知,()相差1,[]与{}相差2。则可以既不需要字典映射也不需要写字符。
3.代码实现
def isValid(self, s):
# 利用map映射字符括号;list实现栈
# 特殊处理:若字符串长度为奇数,则false;空字符串:ture
if len(s)%2 == 1:
return False
elif len(s) == 0:
return True
else:
dicts = {')': '(', ']': '[', '}': '{'}
stack = list()
stack.append(s[0])
for i in range(1,len(s)):
if stack and s[i] in dicts :
if stack[-1] == dicts[s[i]]:
stack.pop()
else:
stack.append(s[i]) # 可将此处改成return False
else:
stack.append(s[i])
return not stack # not stack:stack空则返回ture
def isValid1(self, s):
# 取巧的方式:反复去掉配对的括号,直到没有可去除的括号为止。
if len(s)%2 == 1:
return False
elif len(s) == 0:
return True
else:
s_replace = s.replace('()','').replace('[]','').replace('{}','')
while s_replace < s:
s = s_replace
s_replace = s.replace('()','').replace('[]','').replace('{}','')
return not s_replace