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

  • 相关阅读:
    Visual Studio 2019 使用.Net Core 3.0 一
    Asp.Net真分页技术
    Vue-员工管理系统
    Activex在没有电子秤api的情况下获取串口数据
    C#调用Activex中串口电子秤的数据,并将电子秤的数据显示到前端页面
    C# Datetime.Ticks
    Asp.Net进阶/管家模式+发布订阅模式:练习
    委托解耦
    Asp.Net进阶/值类型与引用类型:复习
    C# 简单日志帮助类LogHelper
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13474051.html
Copyright © 2020-2023  润新知