Less than 1 minute
class Solution {
public int longestSubstring(String s, int k) {
if(s.length() < k){
return 0;
}
int[] nums = new int[26];
char[] chars = s.toCharArray();
for(int i =0;i<chars.length; i++){
nums[chars[i] - 'a']++;
}
for(int i =0;i<chars.length; i++){
int count = nums[chars[i]-'a'];
if(count > 0 && count < k){
int j = i + 1;
while( j < chars.length && chars[j] == chars[i]){
j++;
}
String s1 = s.substring(0,i), s2 = s.substring(j);
return Math.max(longestSubstring(s1, k), longestSubstring(s2, k));
}
}
return chars.length;
}
}
- 分割原理:一个字符串
aabaa
,k=2,那么只要包含b
的子串都不满足,所以就以b
为分割。 - 统计字符串中每个字符的出现次数,以次数< k的字符为分割。剩余的子串,递归做此处理,直至
- 整个子串长度< k (排除)
- 子串中没有出现次数< k的字符