Sliding Window Algorithm Questions

LeetCode 424. Longest Repeating Character Replacement

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.

Algorithm: For a given window, always keep the letter that appears the most and replace other letters. This minimizes replacement times.  For a window of [i, j] with length L = j - i + 1, as long as L - maxFrequency <= k, we can keep extending this window's right bound by 1. As soon as L - maxFrequency > k, we know that we've just reached the limit of all windows that start at index i and the max value of all these windows is L - 1(including the current letter requires k + 1 replacements).  At this point, update the current max value then move forward the left bound of possible windows to i + 1 and decrement the frequency of letter at i by 1. 

When calculating the max frequency in a given window, we don't need to go through the entire frequency array. Since any possible new max frequency can only come from either the new frequency of the newly added letter or the previous max frequency, we just need to compare these two.

class Solution {
    public int characterReplacement(String s, int k) {
        int[] freq = new int[26];
        int start = 0, end = 0, maxFreq = 0, maxLen = 0;
        while(end < s.length()) {
            freq[s.charAt(end) - 'A']++;
            maxFreq = Math.max(maxFreq, freq[s.charAt(end) - 'A']);
            int len = end - start + 1;
            if(len - maxFreq > k) {     
                maxLen = Math.max(maxLen, len - 1);
                freq[s.charAt(start) - 'A']--;
                start++;
            }
            end++;
        }
        return Math.max(maxLen, end - start);
    }
}

猜你喜欢

转载自www.cnblogs.com/lz87/p/10699614.html