Brute Force
Intuition
For every possible substring, count the frequency of each character and determine how many replacements are needed to make all characters the same. The number of replacements needed is the window length minus the count of the most frequent character in that window. If this is at most k, the substring is valid. We track the maximum length among all valid substrings.
Algorithm
- Initialize maxLen to 0.
- For each starting index i, iterate over each ending index j from i to n - 1.
- Maintain a frequency count of characters in the window [i, j].
- Find the maximum frequency character count in the current window.
- If (j - i + 1) - maxFreq <= k, update maxLen with the window size.
- Return maxLen.
O(n^2)SpaceO(1) since the frequency array has at most 26 entriesCode (C++ · Java · Python · Go)
class Solution {
public:
int characterReplacement(string s, int k) {
int maxLen = 0;
int n = s.size();
for (int i = 0; i < n; i++) {
int freq[26] = {};
int maxFreq = 0;
for (int j = i; j < n; j++) {
freq[s[j] - 'A']++;
maxFreq = max(maxFreq, freq[s[j] - 'A']);
if ((j - i + 1) - maxFreq <= k) {
maxLen = max(maxLen, j - i + 1);
}
}
}
return maxLen;
}
};class Solution {
public int characterReplacement(String s, int k) {
int maxLen = 0;
int n = s.length();
for (int i = 0; i < n; i++) {
int[] freq = new int[26];
int maxFreq = 0;
for (int j = i; j < n; j++) {
freq[s.charAt(j) - 'A']++;
maxFreq = Math.max(maxFreq, freq[s.charAt(j) - 'A']);
if ((j - i + 1) - maxFreq <= k) {
maxLen = Math.max(maxLen, j - i + 1);
}
}
}
return maxLen;
}
}def characterReplacement(s: str, k: int) -> int:
max_len = 0
n = len(s)
for i in range(n):
freq = {}
max_freq = 0
for j in range(i, n):
freq[s[j]] = freq.get(s[j], 0) + 1
max_freq = max(max_freq, freq[s[j]])
if (j - i + 1) - max_freq <= k:
max_len = max(max_len, j - i + 1)
return max_lenfunc characterReplacement(s string, k int) int {
maxLen := 0
n := len(s)
for i := 0; i < n; i++ {
freq := [26]int{}
maxFreq := 0
for j := i; j < n; j++ {
freq[s[j]-'A']++
if freq[s[j]-'A'] > maxFreq {
maxFreq = freq[s[j]-'A']
}
if (j-i+1)-maxFreq <= k {
if j-i+1 > maxLen {
maxLen = j - i + 1
}
}
}
}
return maxLen
}