- 找连续相同的字符 + 一个不同的字符 + 连续相同的字符 这种模式。
- 比较字符的当前长度和总长度,如果小于总长度,还可以 + 1(说明可以从不连续的其他地方过来替换不相等的那个)
def maxRepOpt1(self, text):
"""
:type text: str
:rtype: int
"""
counter = Counter(text)
cur = text[0]
res,count = 0,1
for r in range(1,len(text)):
if text[r] == cur: #前面的连续相同的字符
count += 1
else: #一个不同的字符
n_next = r+1 #跳过这个不相等的字符
while n_next < len(text) and text[n_next] == cur: #后面的连续相同的字符
count += 1
n_next += 1
if count < counter[cur]: #看看是否能从其他地方替换
count += 1
res = max(res,count)
cur = text[r] #从不相等的地方接着算
count = 1 #更新count
if count >= 1: #防止都是相等的或就一个字符进不了else循环
if count < counter[cur]: #如果最长的字串都是相等的,进不了else如"acbaaa",也需要进行和上面一样的总数判断一次
count += 1
res = max(res,count)
return res