Untitled
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 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 i=0;i<26;i++) { maxFreq = Math.max(maxFreq,arr[s.charAt(i) - 'A']); } } // Update the maximum length of the valid window maxLength = Math.max(maxLength, j - i + 1); } return maxLength; } } 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 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 if ((j - i + 1) - maxFreq > k) { // Shrink the window from the left arr[s.charAt(i) - 'A']--; i++; maxFreq = 0; for(int i=0;i<26;i++) { maxFreq = Math.max(maxFreq,arr[s.charAt(i) - 'A']); } } // Update the maximum length of the valid window if(j-i+1<=k) maxLength = Math.max(maxLength, j - i + 1); } return maxLength; } }
Leave a Comment