Advertisement
imashutosh51

Longest Substring with At Least K Repeating Characters

Oct 30th, 2022
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. /*
  2. Logic:
  3. Test case: "bbaaacbd"  3
  4. All the characters whose count is less than k can't be inside our answer so whenever we
  5. get those characters,there is two possible answer string before that character and after that
  6. character and pass those strings into the same function.
  7. eg. "bbaaacbd"  k=3
  8.      "bbaaa"  "bd"
  9.      "" "aaa"  ""
  10.      answer="aaa"
  11. */
  12. class Solution {
  13. public:
  14.     int longestSubstring(string s, int k) {
  15.         int n=s.length();  
  16.         if(n==0 || n<k) return 0;   //string size 0 or k>size of string,answer is 0
  17.         if(k<=1) return n;          // if k<=1,then whole string will be our answer.
  18.        
  19.         unordered_map<char,int> mp;
  20.         for(auto itr:s) mp[itr]++;
  21.        
  22.         int l=0;
  23.         while(l<n && mp[s[l]]>=k) l++;   //lth character will be a character which shouldn't
  24.         if(l>= n-1) return l;            // be in the answer,so break the string.
  25.        
  26.         int ans1=longestSubstring(s.substr(0,l),k);
  27.         while(l<n && mp[s[l]]<k) l++;  //remove all those characters whose frequency is
  28.         int ans2=0;                    // less than k.
  29.         if(l<n) ans2=longestSubstring(s.substr(l),k);
  30.         return max(ans1,ans2);
  31.     }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement