zoukankan      html  css  js  c++  java
  • 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即可。

  • 相关阅读:
    hdu 4027 Can you answer these queries?
    hdu 4041 Eliminate Witches!
    hdu 4036 Rolling Hongshu
    pku 2828 Buy Tickets
    hdu 4016 Magic Bitwise And Operation
    pku2886 Who Gets the Most Candies?(线段树+反素数打表)
    hdu 4039 The Social Network
    hdu 4023 Game
    苹果官方指南:Cocoa框架(2)(非原创)
    cocos2d 中 CCNode and CCAction
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13474051.html
Copyright © 2011-2022 走看看