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的字母作为分界点,我写的递归类似线段树,一开始超时了,我也没搞清楚为什么,后来调试的时候发现for循环的时候重复计算了,加个return就过了。
笨拙的代码
class Solution { public: int ans = 0; map<char,int> mp; void dfs(int l, int r, int k, string &s) { if (l > r || r - l + 1 < k) return ; int mark = 0; mp.clear(); for (int i = l; i <= r; ++i) mp[s[i]]++; for (int i = l; i <= r; ++i) { if(mp[s[i]] < k) { dfs(l, i - 1, k, s); dfs(i + 1, r, k, s); return ; mark = 1; } } if (!mark) { ans = max(r - l + 1, ans); } } int longestSubstring(string s, int k) { int n = s.length(); dfs(0, n - 1, k, s); return ans; } };