题目:
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 104.
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.
思路:
这道题目最简单的思路就是用移动窗口来解决。对于一个长度为m的子串而言,我们假设里面出现次数最多的字符的出现次数是n,那么m可以在k次之内被替换成为单一字符的充要条件是m - n <= k。因此,我们仅需要维护一个滑动窗口,使得这个窗口的长度减去出现次数最多的字符的出现次数小于等于k。在遍历的过程中找到这个最长的m即可。
我们下面实现的算法的空间复杂度是O(1),时间复杂度是O(n),这里n是输入字符串的长度。为什么for循环里面的while循环不额外增加时间复杂度呢?这是因为每个字符在while循环内最多被去除一次,因此while总的循环次数不会超过O(n)。
代码:
class Solution {
public:
int characterReplacement(string s, int k) {
int size = s.size();
vector<int> count(26,0);
int begin = 0, maxlen = 0, ans = 0;
for(int end = 0; end < size; ++end) {
maxlen = max(maxlen, ++count[s[end] - 'A']); // s[end] is the new possible dominate character
while(end - begin + 1 - maxlen > k) { // length(substring) - maxlen > k mean we cannot form repeating letters
--count[s[begin++] - 'A'];
}
ans = max(ans, end - begin + 1);
}
return ans;
}
};