题目如下:
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: 4Example 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: 1Constraints:
1 <= text.length <= 20000
text
consist of lowercase English characters only.
解题思路:我的方法是合并相同的连续字符,并记录其连续的个数,例如text="aaabbaaa",解析成char=['a','b','a'],amount=[3,2,3],amount[i]表示char[i]在text中连续出现的次数。要使得只交换一次可以获得的最大值,有这么几种情况:
1. amount[i]是最大值,同时text中除了这一段没有其他地方出现该字符,那么最大值就是amount[i];
2.amount[i]是最大值,同时text中除了这一段没有其他地方出现该字符,但是两者相距超过一个字符的长度,这表明可以交换一个字符到amount[i]对应的这段,最大值是amount[i]+1;
3.amount[i-1]和amount[i+1]对应的字符相同,同时amount[i] = 1,这时最大值是amount[i-1] + amount[i+1] - 1。
代码如下:
class Solution(object): def maxRepOpt1(self, text): """ :type text: str :rtype: int """ dic = {} char = [] amount = [] last = None count = 1 text += '#' for i in text: dic[i] = dic.setdefault(i,0) + 1 if last == None: last = i elif i == last: count += 1 else: char.append(last) amount.append(count) count = 1 last = i res = 0 for i in range(len(char)): if i > 0 and i < len(char) - 1 and char[i-1] == char[i+1] and amount[i] == 1: v = amount[i-1] + amount[i+1] if dic[char[i-1]] > v: v += 1 res = max(res,v) if dic[char[i]] > amount[i]:res = max(res,amount[i] + 1) else:res = max(res,amount[i]) return res