Count substrings with each character occurring at most k times in C++

C++Server Side ProgrammingProgramming

We are given a string str. The goal is to count the number of substrings in str that have each character occurring utmost k times. For example if input is “abc” and k=1, the substrings will be “a”, “b”, “c”, “ab”, “bc”, “abc”.

Let us understand with examples.

Input − str=”abaefgf”

Output − Count of substrings with same first and last characters are &mmius; 9

Explanation − Substrings will be

“a”, “b”, “a”, “e” ,”f”, “g”, “f”, “aba”, “fgf”. Total 9.

Input − str=”abcdef”

Output − Count of substrings with same first and last characters are: 6

Explanation − Substrings will be -

“a” , “b” , “c”, “d”, “e” ,”f”. Total 6

The approach used in the below program is as follows

There can be multiple approaches to solve the given problem i.e. naive approach and efficient approach. So let’s first look at the naive approach. We will pass substrings of every length to a function check(). If that substring starts and ends with the same character then increment the count.

  • Take string str. Calculate the length as str.size().

  • Function check(string str) takes substring str and checks if it’s first and last character are the same. ( str[0]==str[length-1] ). If true, return 1.

  • Function check_Start_End(string str, int length) takes str and its length as input and returns the count of substrings of str which start and end with the same character.

  • Take the initial count as 0.

  • Traverse str using two for loops. From i=0 to i<length and inner j=1 to j=length-1.

  • We will get all substrings using substr(i,j) of all lengths. Pass each substring to check(). If it returns 1, increment count.

  • At the end of both for loops count will have a number of substrings of str with the same start and end character.

  • Return count as the desired result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int count_k(string str, int len, int k){
   int count = 0;
   int arr[26];
   for (int i = 0; i < len; i++){
      memset(arr, 0, sizeof(arr));
      for (int j = i; j < len; j++){
         arr[str[j] - 'a']++;
         if (arr[str[j] - 'a'] <= k)
            { count++; }
         else
            { break; }
      }
   }
   return count;
}
int main(){
   string str = "bbddehj";
   int k = 1;
   int length = str.length();
   cout<<"Count of substrings with each character occurring at most k times are: "<<count_k(str,
length, k);
   return 0;
}

Output

If we run the above code it will generate the following output -

Count of substrings with each character occurring at most k times are: 14
raja
Published on 01-Dec-2020 12:12:12
Advertisements