您的位置:首页 > 其它

Longest Substring with At Least K Repeating Characters

2018-01-03 00:00 513 查看
问题:

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.

解决:

① 思路是扫描出现次数小于k的字母,然后将它们作为分隔符,然后就将这些子串划分成原问题的子问题,递归求解。

class Solution { //5ms
public int longestSubstring(String s, int k) {
if (s.length() == 0) return 0;
int[] hash = new int[26];
for (char c : s.toCharArray()){
hash[c - 'a'] ++;
}
int[] check = new int[26];
for (int i = 0;i < 26;i ++){
if (hash[i] < k) check[i] = -1;//标记出个数小于k的字符
}
int res = 0;
int start = 0;
for (int i = 0;i < s.length();i ++){
if (check[s.charAt(i) - 'a'] == -1){
res = Math.max(res,longestSubstring(s.substring(start,i),k));
start = i + 1;
}
}
if (start == 0){
return s.length();
}else {
res = Math.max(res,longestSubstring(s.substring(start,s.length()),k));
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: