1246 · Longest Repeating Character Replacement
Algorithms
Medium
Accepted Rate
45%
Description
Solution
Notes
Discuss
Leaderboard
Record
Description
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.
Both the string’s length and k will not exceed 10^4.
Example
Example1
Input:
“ABAB”
2
Output:
4
Explanation:
Replace the two 'A’s with two 'B’s or vice versa.
Example2
Input:
“AABABBA”
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.
Tags
Company
Pocket Gems
解法1:
class Solution {
public:
/**
* @param s: a string
* @param k: a integer
* @return: return a integer
*/
int characterReplacement(string &s, int k) {
int len = s.size();
if (len == 0) return 0;
if (k == 0) return 1;
int i = 0, j = 0;
vector<int> freq(26, 0);
int maxLen = 1, maxFreq = 0;
for (i = 0; i < len; ++i) {
j = max(i, j);
while (j < len && (j - i - maxFreq <= k)) {
freq[s[j] - 'A']++;
maxFreq = max(maxFreq, freq[s[j] - 'A']);
j++;
}
if (j - i - maxFreq > k) maxLen = max(maxLen, j - i - 1);
else {
maxLen = max(maxLen, j - i);
}
freq[s[i] - 'A']--;
}
return maxLen;
}
};
二刷:
class Solution {
public:
/**
* @param s: a string
* @param k: a integer
* @return: return a integer
*/
int characterReplacement(string &s, int k) {
int n = s.size();
int left = 0, right = 0;
int freq[26] = {0}, maxFreq = 0;
int maxLen = 0;
while (right < n) {
char ch = s[right];
int index = ch - 'A';
freq[index]++;
if (maxFreq < freq[index]) {
maxFreq = max(maxFreq, freq[index]);
//maxFreqIndex = index;
}
right++;
//while (left < right && right - left - maxFreq > k) {
while (right - left - maxFreq > k) { //注意:这里用if也对,因为满足right-left-maxFreq>k的情形就是因为right向右移动了一位,所以这里left最多也只需要往右移动一位即可。所以,如果用while的话,maxFreq不用改。
char ch = s[left];
int index = ch - 'A';
freq[index]--;
left++;
}
maxLen = max(maxLen, right - left);
}
return maxLen;
}
};