码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Longest Substring with At Least K Repeating Characters

时间:2016-12-01 14:23:42      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:bst   new   case   span   find   repeat   slow   longest   ide   

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

标签:bst   new   case   span   find   repeat   slow   longest   ide   

原文地址:http://www.cnblogs.com/EdwardLiu/p/6121232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!