424. Longest Repeating Character Replacement

Given an array A of 0s and 1s, we may change up to K values from 0 to 1.

Return the length of the longest (contiguous) subarray that contains only 1s. 

 

Example 1:

Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation: 
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.

Example 2:

Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation: 
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.

 

Note:

  1. 1 <= A.length <= 20000
  2. 0 <= K <= A.length
  3. A[i] is 0 or 1 
class Solution {
    public int characterReplacement(String s, int k) {
        int[] count = new int[26];
        int left = 0, maxcount = 0, res = 0;
        
        for(int right = 0; right < s.length(); right++) {
            maxcount = Math.max(maxcount, ++count[s.charAt(right) - 'A']);
            while(right - left + 1 - maxcount > k) {
                --count[s.charAt(left) - 'A'];
                left++;
            }
            res = Math.max(res, right - left + 1);
        }
        return res;
    }
}

sliding window, 这题维护一个left - right 的window。

想想:总功能再left - right这个substring修改k次,那我们首先要找到这个substring里哪个char占的最多,那说明要把剩下的部分改成这个char。所以window维护的是一个长为right - left + 1的string,最多修改k次后变成所有char相同。

首先获得maxcount,这就是这个window里哪个char最多,然后如果k次兜不住了,就要left++维护window。最后返回最大的window即可。

posted @ 2020-08-11 10:30  Schwifty  阅读(93)  评论(0编辑  收藏  举报