[LeetCode] Swap For Longest Repeated Character Substring

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
int maxRepOpt1(string text) {
int res = 0, n = text.length(), l = 0, r = 0;
unordered_map<char, int> freq;
for(auto& ch : text) ++freq[ch];
while(r < n) {
int temp = -1, noteq = 0;
while(r < n) {
if(text[l] != text[r]) {
if(++noteq >= 2) break;
temp = r;
}
++r;
int remain = freq[text[l]] - (r - l);
if(remain < 0) break;
res = max(res, r - l);
}
if(temp == -1) l = r;
else r = l = temp;
}
l = r = n - 1;
while(l >= 0) {
int temp = -1, noteq = 0;
while(l >= 0) {
if(text[l] != text[r]) {
if(++noteq >= 2) break;
temp = l;
}
--l;
int remain = freq[text[r]] - (r - l);
if(remain < 0) break;
res = max(res, r - l);
}
if(temp == -1) r = l;
else r = l = temp;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/16/PS/LeetCode/swap-for-longest-repeated-character-substring/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.