[LeetCode] Longest Repeating Character Replacement

424. Longest Repeating Character Replacement

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int characterReplacement(string s, int k) {
unordered_map<char, int> counter;
int res = 0, l = 0, r = 0, ma = 0, n = s.length();
while(r < n) {
while(r < n and r - l - ma <= k) {
res = max(res, r - l);
ma = max(ma, ++counter[s[r++]]);
}

while(l < r and r - l - ma > k) {
--counter[s[l++]];
}
}
res = max(res, r - l);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/19/PS/LeetCode/longest-repeating-character-replacement/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.