首页 > 代码库 > Leetcode: Longest Substring with At Least K Repeating Characters

Leetcode: Longest Substring with At Least K Repeating Characters

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.

Analysis:

Given a string s, find out all chars that are invalid (i.e., count < k). The longest substring must reside in one of the substrings divided by those invalid chars. We find out all those possible substrings and recursively address each of them.

NOTE: repeatedly using s.charAt() is actually very slow. So we convert the string to charArray in the first place

 1 public class Solution {
 2     public int longestSubstring(String s, int k) {
 3         return longestSubstring(s.toCharArray(), 0, s.length()-1, k);
 4     }
 5     
 6     public int longestSubstring(char[] arr, int start, int end, int k) {
 7         if (end < start) return 0;
 8         if (end-start+1 < k) return 0;
 9         int[] count = new int[26];
10         for (int i=start; i<=end; i++) {
11             count[arr[i]-‘a‘]++;
12         }
13         for (int i=0; i<26; i++) {
14             if (count[i] == 0) continue;
15             if (count[i] < k) {
16                 int j = start;
17                 for (; j<=end; j++) {
18                     if (arr[j] == (char)(‘a‘+i)) break;
19                 }
20                 int left = longestSubstring(arr, start, j-1, k);
21                 int right = longestSubstring(arr, j+1, end, k); 
22                 return Math.max(left, right);
23             }
24         }
25         return end-start+1;
26     }
27 }

 

Leetcode: Longest Substring with At Least K Repeating Characters