Longest Substring with At Least K Repeating Characters in C++


Suppose we have a string s, and we have to find the length of the longest substring T of that given string (consists of lowercase letters only) such that every character in T appears no less than k times. So if the string is “ababbc” and k = 2, then the output will be 3 and longest substring will be “ababb”, as there are two a’s and three b’s.

To solve this, we will follow these steps −

  • create one recursive function called longestSubstring(), this takes string s and size k
  • if k = 1, then return the size of the string
  • if size of string < k, then return 0
  • create one array c of size 26, and fill this with -1
  • n := size of the string
  • for i in range 0 to n
    • if c[s[i] – ‘a’] = -1, then c[s[i] – ‘a’] := 1, otherwise increase c[s[i] – ‘a’] by 1
  • badChar := ‘*’
  • for i in range 0 to 25
    • if c[i] is not -1 and c[i] < k, then badChar := i + ‘a’ and come out from the loop
  • if badChar = ‘*’, then return n
  • v := another array of strings by splitting the original string using badChar
  • ans := 0
  • for i in range 0 to size of v
    • ans := max of ans and longestSubstring(v[i], k)
  • return ans

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   vector <string> splitString(string s, char x){
      string temp = "";
      vector <string> res;
      for(int i = 0; i < s.size(); i++){
         if(s[i] == x){
            if(temp.size())res.push_back(temp);
            temp = "";
         }
         else temp += s[i];
      }
      if(temp.size())res.push_back(temp);
      return res;
   }
   int longestSubstring(string s, int k) {
      if(k == 1)return s.size();
      if(s.size() < k )return 0;
      vector <int> cnt(26, -1);
      int n = s.size();
      for(int i = 0; i < n; i++){
         if(cnt[s[i] - 'a'] == -1) cnt[s[i] - 'a'] = 1;
         else cnt[s[i] - 'a']++;
      }
      char badChar = '*';
      for(int i = 0; i < 26; i++){
         if(cnt[i] != -1 && cnt[i] < k){
            badChar = i + 'a';
            break;
         }
      }
      if(badChar == '*')return n;
      vector <string> xx = splitString(s, badChar);
      int ans = 0;
      for(int i = 0; i < xx.size(); i++)ans = max(ans, longestSubstring(xx[i], k));
      return ans;
   }
};
   main(){
   Solution ob;
   cout << ob.longestSubstring("ababbc", 2);
}

Input

"ababbc"
2

Output

5

Updated on: 28-Apr-2020

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements