1156. Swap For Longest Repeated Character Substring
Description
You are given a string text
. You can swap two of the characters in the text
.
Return 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" with length 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" with length 6.
Example 3:
Input: text = "aaaaa" Output: 5 Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.
Constraints:
1 <= text.length <= 2 * 104
text
consist of lowercase English characters only.
Solution
swap-for-longest-repeated-character-substring.py
class Solution:
def maxRepOpt1(self, text: str) -> int:
A = [[c, len(list(x))] for c,x in itertools.groupby(text)]
count = collections.Counter(text)
res = max(min(count[c], x + 1) for c,x in A)
for i in range(1, len(A) - 1):
if A[i - 1][0] == A[i + 1][0] and A[i][1] == 1:
res = max(res, min(A[i - 1][1] + A[i + 1][1] + 1, count[A[i - 1][0]]))
return res