Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- Test case: "bbaaacbd" 3
- All the characters whose count is less than k can't be inside our answer so whenever we
- get those characters,there is two possible answer string before that character and after that
- character and pass those strings into the same function.
- eg. "bbaaacbd" k=3
- "bbaaa" "bd"
- "" "aaa" ""
- answer="aaa"
- */
- class Solution {
- public:
- int longestSubstring(string s, int k) {
- int n=s.length();
- if(n==0 || n<k) return 0; //string size 0 or k>size of string,answer is 0
- if(k<=1) return n; // if k<=1,then whole string will be our answer.
- unordered_map<char,int> mp;
- for(auto itr:s) mp[itr]++;
- int l=0;
- while(l<n && mp[s[l]]>=k) l++; //lth character will be a character which shouldn't
- if(l>= n-1) return l; // be in the answer,so break the string.
- int ans1=longestSubstring(s.substr(0,l),k);
- while(l<n && mp[s[l]]<k) l++; //remove all those characters whose frequency is
- int ans2=0; // less than k.
- if(l<n) ans2=longestSubstring(s.substr(l),k);
- return max(ans1,ans2);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement