1156. Swap For Longest Repeated Character Substring
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 < = t e x t . l e n g t h < = 2 ∗ 10 4 1 <= text.length <= 2 * 10^4 1<=text.length<=2∗104
- text consist of lowercase English characters only.
From: LeetCode
Link: 1156. Swap For Longest Repeated Character Substring
Solution:
Ideas:
count total letters, scan same-character blocks, then either extend one block by 1 or merge two blocks separated by one different character.
Code:
c
int maxRepOpt1(char* text) {
int total[26] = {0};
int n = 0;
while (text[n]) {
total[text[n] - 'a']++;
n++;
}
int ans = 0;
for (int i = 0; i < n; ) {
int j = i;
while (j < n && text[j] == text[i]) {
j++;
}
int ch = text[i] - 'a';
int len1 = j - i;
// Case 1: extend this block by swapping one same char from elsewhere
if (total[ch] > len1)
ans = ans > len1 + 1 ? ans : len1 + 1;
else
ans = ans > len1 ? ans : len1;
// Case 2: combine two same-char blocks separated by one different char
int k = j + 1;
if (j < n && k < n && text[k] == text[i]) {
while (k < n && text[k] == text[i]) {
k++;
}
int len2 = k - (j + 1);
int combined = len1 + len2;
if (total[ch] > combined)
combined++;
if (combined > ans)
ans = combined;
}
i = j;
}
return ans;
}