Given a string text
, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters.
Example 1:
Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa", which its length is 3.
Example 2:
Input: text = "aaabaaa" Output: 6 Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa", which its length is 6.
Example 3:
Input: text = "aaabbaaa" Output: 4
Example 4:
Input: text = "aaaaa" Output: 5 Explanation: No need to swap, longest repeated character substring is "aaaaa", length is 5.
Example 5:
Input: text = "abcdef" Output: 1
Constraints:
1 <= text.length <= 20000
text
consist of lowercase English characters only.
思路:关键在于判断相邻的部分是否能合并
from collections import Counter
class Solution(object):
def maxRepOpt1(self, text):
"""
:type text: str
:rtype: int
"""
helper=[]
n=len(text)
i=0
while i<n:
j=i
while j<n and text[j]==text[i]: j+=1
helper.append((text[i],j-i))
i=j
count = Counter([s[0] for s in helper])
res=0
for c,l in helper: # long distance switch
if count[c]>1: res=max(res, l+1)
else: res=max(res, l)
for i in range(len(helper)-2): # merge neighbor
c1,l1 = helper[i]
c2,l2 = helper[i+2]
if c1==c2 and helper[i+1][1]==1:
if count[c1]>2: res=max(res, l1+l2+1)
else: res=max(res ,l1+l2)
return res