Untitled
unknown
plain_text
a year ago
1.4 kB
5
Indexable
public class Solution {
public int characterReplacement(String s, int k) {
int n = s.length();
int[] hash = new int[26]; // Frequency array for characters
int maxFreq = 0; // Maximum frequency of any character in the window
int maxLength = 0;
for (int i = 0; i < n; i++) {
// Reset the hash array and maxFreq for each new starting point
for (int j = 0; j < 26; j++) {
hash[j] = 0;
}
maxFreq = 0;
for (int j = i; j < n; j++) {
// Update the frequency of the current character
hash[s.charAt(j) - 'A']++;
// Update the maximum frequency of any character in the current substring
maxFreq = Math.max(maxFreq, hash[s.charAt(j) - 'A']);
// Calculate the number of changes needed
int changes = (j - i + 1) - maxFreq;
if (changes <= k) {
// Update the maximum length if the current substring is valid
maxLength = Math.max(maxLength, j - i + 1);
} else {
// Break out of the loop if the substring is no longer valid
break;
}
}
}
return maxLength;
}
}
Editor is loading...
Leave a Comment