1. 读懂题目
2. 分析,推导解法,产生思路。
特殊情况处理即个数不匹配;
(1)list模拟栈:.append .pop;字典的键值利用;
(2)repalce()子串替换
# 反复替换: "([])" 停止条件:没有能删除的配对字符即此轮字符长度与上轮一致;
3 代码实现:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) % 2 == 1: # 特殊情况,个数不匹配
return False
# 1 list模拟栈:.append .pop
stack = list()
pairs = { ")": "(", "]": "[", "}": "{",}
ch = 0
while ch < len(s) : # 遍历字符
if s[ch] in pairs: # 若为字典的键即右括号则进入匹配
if not stack or stack[-1] != pairs[s[ch]]: # 栈为空或不能匹配则False
return False
stack.pop() # 匹配则出栈
else: # 若为字典的键即左括号则入栈
stack.append(s[ch]) # 入栈
ch = ch + 1
return not stack
# 2 python字符串函数
# repalce()子串替换
# 反复替换: "([])" 停止条件:没有能删除的配对字符即此轮字符长度与上轮一致;
# 2.1 引入额外的s_sub子串
s_sub = s.replace('()', '').replace('{}','').replace('[]','')
while len(s_sub) < len(s):
s = s_sub # 替换字符
s_sub = s.replace('()', '').replace('{}','').replace('[]','')
return not s_sub
# 2.2 引入额外的len_before字段
while True:
len_before = len(s) # 记录替换之前的字符串长度
s = s.replace('()', '').replace('{}','').replace('[]','') # 字串替换
if len_before == len(s): #字串长度前后比较
break
return not s
# 2.1与2.2的内存与执行时间差距不大;1(4ms)比2(51ms)执行速度快很多,内存差距不大