LeetCode 395. 至少有 K 个重复字符的最长子串 0ms

LeetCode 395. 至少有 K 个重复字符的最长子串 0ms

不要问为什么这么快,问就是代码写得好。空间换的

image-20210227165512964

题目描述

给你一个字符串 s 和一个整数 k ,请你找出 s 中的最长子串, 要求该子串中的每一字符出现次数都不少于 k 。返回这一子串的长度。

分治思路

这个思路强就强在不直接去找最长子串,而是通过不符合条件的字符进行分段求解。从问题的反面下手,解决问题

  1. 记录每个字符出现的次数

  2. 如果不存在出现次数低于k的字符,则返回这个字符串的长度。否则进入3

  3. 将不合符的区间进行分治。

    image-20210227170417342

代码如下

public int longestSubstring(String s, int k) {
    if(k==1){
        return s.length();
    }
    char[] chars = s.toCharArray();
    return longestSubstring(chars, k ,0 ,s.length());
}

public int longestSubstring(char[] chars, int k,int start, int end) {
    if(end-start<k) return 0;
    int[] count = new int[26];
    int maxLen = 0;
    int sentry = start;
    // 统计各字符出现次数
    while(start<end) count[chars[start++] - 'a']++;
    start =sentry;
    // start<end && (count[chars[start++]-'a'] 为什么有问题
    // 用于判断是否存在不合法的字符
    while (start<end && (count[chars[start]-'a'])>=k){
        start++;
    }
    // 不存在不合法的字符,所有字符出现次数都大于等于k
    if(start==end)
        return end - sentry;
    
    start = sentry;
    while (end - start >= k) {
        // 取第一个有效字符
        while (start < end && count[chars[start] - 'a'] < k) {
            start++;
        }
        sentry = start;
        // 之后的第一个无效字符
        while (start < end && count[chars[start] - 'a'] >= k) {
            start++;
        }
        // 长度小于k则不进行递归求解
        if (start - sentry >= k) {
            maxLen = Math.max(maxLen, longestSubstring(chars, k, sentry, start));
        }

    }
    return maxLen;

}

代码中注释里的问题来位大哥指点一二。。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值