欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Longest Substring with At Least K Repeating Characters

程序员文章站 2024-03-06 20:37:44
...

https://www.lintcode.com/problem/longest-substring-with-at-least-k-repeating-characters/description

public class Solution {
    private int max = 0;
    /**
     * @param s: a string
     * @param k: an integer
     * @return: return an integer
     */
    public int longestSubstring(String s, int k) {
        // write your code here
        recursion(s, k);
        return max;
    }

    private void recursion(String s, int k) {
        int[] target = new int[26];
        char[] chars = s.toCharArray();
        for (char c : chars) {
            target[c - 'a']++;
        }
        int lastIndex = 0;
        for (int i = 0; i <= chars.length; i++) {
            if (i == chars.length) {
                if (lastIndex != 0) {
                    recursion(s.substring(lastIndex, i), k);
                    lastIndex = i + 1;
                }
                break;
            }
            char aChar = chars[i];
            if (target[aChar - 'a'] < k) {
                recursion(s.substring(lastIndex, i), k);
                lastIndex = i + 1;
            }
        }
        if (lastIndex == 0) {
            max = Math.max(max, s.length());
        }
    }
}