Leetcode 395. Longest Substring with At Least K Repeating Characters 至少K重复最长子序列 解题报告

1 解题思想

题目意思是说,给一个字符串和一个K,现在要找到一个子串,这个子串里面的每个出现的字符都至少出现K次。

这个不是一般的DP或者暴力的解决方式,要用一下递归:

1、统计每个字母【只有小写】出现的次数
2、找出不合法的字符【出现了,但是次数不够K】
3、如果没有任何不合法字符,那么返回串的长度
4、如果有不合法的字符,那么将这个串按照本轮不合法的字符位置切开(一个不合法的字符就切一刀),切开后的每一个子串递归执行1,取最长的返回

2 原题

Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times. 
Example 1: 
Input:
s = "aaabb", k = 3

Output:
3

The longest substring is "aaa", as 'a' is repeated 3 times.

Example 2: 
Input:
s = "ababbc", k = 2

Output:
5

The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

3 AC解

public class Solution {
    public int longestSubstring(String s, int k) {
        //System.out.println(s);
        int n = s.length();
        if(n < k) return 0;
        int counter[] = new int[26];
        boolean valid[] = new boolean[26];
        char ss[] = s.toCharArray();
        //统计每个字符的长度
        for(int i=0;i'a']++;
        //检查当前字符串是否是完全满足的
        boolean fullValid = true;
        //判断每个字符的出现条件是否合适,即,要么不出现,要么出现了不少于k
        for(int i=0;i<26;i++){
            if(counter[i]>0 && counter[i]false;
                fullValid = false;
            }
            else valid[i] = true;
        }
        if(fullValid) return s.length();
        int max = 0;
        int lastStart=0;
        //把不符合要求的断开,然后依次检查 取最大
        for(int i=0;iif(valid[ss[i] - 'a'] == false){
               // System.out.println(lastStart+"  "+i);
                max = Math.max(max,longestSubstring(s.substring(lastStart,i),k));
                lastStart = i + 1;
            }
        }
        max = Math.max(max,longestSubstring(s.substring(lastStart,n),k));
        return max;

    }
}

你可能感兴趣的:(leetcode-java)