【LeetCode】 395. Longest Substring with At Least K Repeating Characters

来源:互联网 发布:澳门银河网络平台 编辑:程序博客网 时间:2024/06/12 10:13

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 = 3Output:3The longest substring is "aaa", as 'a' is repeated 3 times.

Example 2:

Input:s = "ababbc", k = 2Output:5The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

public class Solution {    public int longestSubstring(String s, int k) {        char[] array = s.toCharArray();        return helper(array, 0, s.length(), k);    }        private int helper(char[] array, int start, int end, int k) {        if (end - start < k) {            return 0;        }        int[] count = new int[26];        for (int i = start; i < end; i++) {            count[array[i] - 'a']++;        }        for (int i = 0; i < 26; i++) {            if (count[i] < k && count[i] > 0) {                for (int j = start; j < end; j++) {                    if (array[j] == i + 'a') {                        int left = helper(array, start, j, k);                        int right = helper(array, j + 1, end, k);                        return Math.max(left, right);                    }                }            }        }        return end - start;    }}


0 0