395. Longest Substring with At Least K Repeating Characters

Find the length of the longest substringTof a given string (consists of lowercase letters only) such that every character inTappears no less thanktimes.

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.

tag: two pointers, DFS

class Solution {
    public int longestSubstring(String s, int k) {
        char[] cArray = s.toCharArray();
        return dfs(cArray, 0, s.length(), k);
    }

    private int dfs(char[] cArray, int start, int end, int k){
        if (end - start < k) return 0;

        int[] count = new int[26];
        for (int i = start; i < end; i++){
            int index = cArray[i] - 'a';
            count[index]++;
        }

        for (int i = 0; i < 26; i++){
            if (count[i] > 0 && count[i] < k){
                for (int j = start; j < end; j++){
                    if (cArray[j] == i + 'a'){
                        int left = dfs(cArray, start, j, k);
                        int right = dfs(cArray, j + 1, end, k);

                        return Math.max(left, right);
                    }
                }
            }
        }

        return end - start;
    }
}

O(n^2)

results for ""

    No results matching ""