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即可。

  • 相关阅读:
    vue (v-if show 问题)
    vue 打包成 apk 文件(修改路径)
    移动端meta几个值的设置以及含义
    vue-cli 搭建
    call() 和 apply() 的作用和区别
    关于闭包的理解
    js的style和getArribute("属性名")
    vue的生命周期
    css3新特性选择器(补充)
    css3的新特性选择器-------属性选择器
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13474051.html
Copyright © 2011-2022 走看看