您的位置:首页 > 编程语言 > C语言/C++

leetcode_[python/C++]_395_Longest Substring with At Least K Repeating Characters

2016-11-13 11:05 561 查看
题目链接

【题目】

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约束条件下递归搜索不满足条件的字符位置的左边字符串和右边的字符串,从而记录最大值

想一想还是比较巧妙的

比如:

“abbcadda" 2

step 1: str = "abbcadda" 不满足条件的字符为c,因为只有c不满足至少重复2次,所以递归索引左右边字符串"abb" ,”adda"

----------------------------------------------------------------------------左

step 2: str1 = "abb"  不满足条件的字符为a,递归”“ 和”bb"

---------------------左

step 3:str2 = ""

---------------------右

step 4:str3 = "bb" 满足条件,maxlen = 2

----------------------------------------------------------------------------右

step 5:str4 = "adda" 满足条件,maxlen = 4 > 2 

所以maxlen = 4, 即“adda"

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

先说一下递归的方法:

C++:

int longestSubstring(const string &s, int k) {
return helper(s, 0, s.size(), k);
}
int helper(const string &s, int beg, int end, int k){
if(end - beg < k) return 0;
int cnt[26]{};
for(int i = beg; i < end; ++i) ++cnt[s[i]-'a'];
for(int i = 0; i < 26; ++i)
if (cnt[i] && cnt[i] < k)
for(int j = beg; j < end; ++j)
if(s[j] == i + 'a')
return max(helper(s, beg, j, k), helper(s, j + 1, end, k));
return end - beg;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode