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;

}

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

猜你喜欢

转载自blog.csdn.net/Dwd_shuai/article/details/114181248