# 424. Longest Repeating Character Replacement

Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.

Note:
Both the string’s length and k will not exceed 10 4.

Example 1:

``````**Input:**
s = "ABAB", k = 2

**Output:**
4

**Explanation:**
Replace the two 'A's with two 'B's or vice versa.
``````

Example 2:

``````**Input:**
s = "AABABBA", k = 1

**Output:**
4

**Explanation:**
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
``````

``````class Solution {
public:
int characterReplacement(string s, int k) {
int res = 0, maxCnt = 0, start = 0;
vector<int> counts(26, 0);
for (int i = 0; i < s.size(); ++i) {
maxCnt = max(maxCnt, ++counts[s[i] - 'A']);
while (i - start + 1 - maxCnt > k) {
--counts[s[start] - 'A'];
++start;
}
res = max(res, i - start + 1);
}
return res;
}
};
``````

Longest Substring with At Least K Repeating Characters

Longest Substring with At Most K Distinct Characters

Longest Substring with At Most Two Distinct Characters

Longest Substring Without Repeating Characters

https://leetcode.com/problems/longest-repeating-character-replacement/

https://leetcode.com/problems/longest-repeating-character-replacement/discuss/91271/Java-12-lines-O(n)-sliding-window-solution-with-explanation

https://leetcode.com/problems/longest-repeating-character-replacement/discuss/91285/Sliding-window-similar-to-finding-longest-substring-with-k-distinct-characters

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation