Give you a string s and an integer k. Please find the longest substring in s, and require that each character in the substring appear more than k. Returns the length of this substring.
Example 1:
Input: s = "aaabb", k = 3
Output: 3
Explanation: The longest substring is "aaa", where'a ' is repeated 3 times.
Example 2:
Input: s = "ababbc", k = 2
Output: 5
Explanation: The longest substring is "ababb", where'a' is repeated 2 times and'b' is repeated 3 times.
analysis:
At first I wanted to use a sliding window, but found it difficult to judge the conditions for moving the left and right borders. If the sliding window must be used, a loop of enumerating 26 character types needs to be set in the outer layer (that is, assuming that there is 1 type of character in the current string -> 26 Different characters), and then adopted the method of divide and conquer, first count the number of occurrences of each character, and then re-traverse the string, encounter an element that does not meet the requirements, use the element as a mark for segmentation, and cut out several For each substring, go to recursive statistics and judgment, and finally record the longest substring in each recursive branch, which is the result.
#include <sstream>
class Solution {
public:
int longestSubstring(string s, int k) {
if(k < 2) return s.size();
if(s.size() < k) return 0;
unordered_set<char> chars(s.begin(), s.end());
unordered_map<char, int> counter;
for(auto c : s){
counter[c]++;
}
for(char c : chars){
vector<string> t;
// 因为当前这个元素c,使得所有带c的子串都无法满足要求
if(counter[c] < k){
split(s, t, c);
/*
for(auto tt : t){
cout << tt << endl;
}*/
int res = 0;
for(auto ss : t){
res = max(res, longestSubstring(ss, k));
}
return res;
}
}
return s.size();
}
void split(const string& s, vector<string>& sv, const char flag = ' '){
istringstream iss(s);
string temp;
while(getline(iss, temp, flag)){
sv.push_back(temp);
}
}
};