Untitled
unknown
plain_text
a year ago
2.8 kB
5
Indexable
public class Solution {
public int characterReplacement(String s, int k) {
int n = s.length();
int[] arr = new int[26]; // To count frequencies of characters in the window
int maxFreq = 0; // Maximum frequency of a single character in the current window
int maxLength = 0;
int i = 0; // Left pointer of the window
int j = 0;
while(j<n){ // Right pointer of the window
// Update the frequency of the current character
arr[s.charAt(j) - 'A']++;
// Update the maximum frequency of any character in the window
maxFreq = Math.max(maxFreq, charCount[s.charAt(j) - 'A']);
// Check if the window is valid:
// Total characters minus the most frequent character count should be <= k
while ((j - i + 1) - maxFreq > k) {
// Shrink the window from the left
arr[s.charAt(i) - 'A']--;
i++;
maxFreq = 0;
for(int p=0;p<26;p++)
{
maxFreq = Math.max(maxFreq,arr[p]);
}
}
// Update the maximum length of the valid window
maxLength = Math.max(maxLength, j - i + 1);
j++;
}
return maxLength;
}
}
class Solution {
public int characterReplacement(String s, int k) {
int n = s.length();
int[] arr = new int[26]; // To count frequencies of characters in the window
int maxFreq = 0; // Maximum frequency of a single character in the current window
int maxLength = 0;
int i = 0; // Left pointer of the window
int j = 0;
while(j<n){ // Right pointer of the window
// Update the frequency of the current character
arr[s.charAt(j) - 'A']++;
// Update the maximum frequency of any character in the window
maxFreq = Math.max(maxFreq, arr[s.charAt(j) - 'A']);
// Check if the window is valid:
// Total characters minus the most frequent character count should be <= k
if ((j - i + 1) - maxFreq > k) {
// Shrink the window from the left
arr[s.charAt(i) - 'A']--;
i++;
maxFreq = 0;
for(int p=0;p<26;p++)
{
maxFreq = Math.max(maxFreq,arr[p]);
}
}
// Update the maximum length of the valid window
if((j - i + 1) - maxFreq <= k)
maxLength = Math.max(maxLength, j - i + 1);
j++;
}
return maxLength;
}
}Editor is loading...
Leave a Comment