【題目】
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;
}