395. Longest Substring with At Least K Repeating Characters
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.
class Solution { public: //分治加递归 int longestSubstring(string s, int k) { if(s.size()<k) return 0; vector<int> m(26,0); for(int i=0;i<s.size();i++){ m[s[i]-'a']++; } bool flag = true; int j=0; for(j=0;j<s.size();j++){ if(m[s[j]-'a']<k){ flag = false; break; } } if( flag == true) return s.size(); //否则以第一次出现不符合要求的s[i]的位置为分割,左右分治 int res1 = longestSubstring(s.substr(0,j),k); int res2 = longestSubstring(s.substr(j+1),k); return max(res1,res2); } };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步