Leetcode: Longest Substring with At Least K Repeating Characters

Posted neverlandly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode409. Longest Palindrome

leetcode:longest-increasing

[Leetcode]Longest Palindromic Substring

leetcode longest consecutive sequence

LeetCode Longest Increasing Subsequence

#Leetcode# 14. Longest Common Prefix