Count subsequence of length three in a given string in C++

C++Server Side ProgrammingProgramming

We are given string str and a substring sub_str of length 3. The goal is to find the count of subsequence sub_str in str. Example “act” is thrice in “cataract” ( cataract, cataract, cataract ).

Let us understand with examples.

Input − str= “settlement” sub_str=”set”

Output − Count of a subsequence of length three in a given string are: 5

Explanation − Subsequences will be −

1. set tlement,
2. se t t lement,
3. se ttlemen t,
4. s ettl e men t,
5. settlem e n t

Input − str= “knowledge” sub_str=”now”

Output − Count of a subsequence of length three in a given string is − 1

Explanation − Subsequences will be − know ledge

The approach used in the below program is as follows

We will traverse the string str using a for loop. If any str[i]==sub_str[0] then compare next character sub_str[1] with str[ current i to i<length ] , if match found at index j, then compare last character sub_str[2] with str[ current j to j<length ]. If both matches are found, increment count.

  • Take string as str and substring as sub_str.

  • Function subset_occurrence(string str, int length, string sub_str) takes strings and returns a count of subsequences same as sub_str in str.

  • Traverse str using for loop. From i=0 to i<length.

  • If any str[i]==sub_str[0], first character found. Check next by j=i+1 to j<length.

  • If any str[j]==sub_str[1], the second character matched. Check next by k=j+1 to k<length.

  • If str[k]==sub_str[2]. Increment count.

  • Return count as result.

Example

 Live Demo

#include<iostream>
using namespace std;
int subset_occurrence(string str, int length, string sub_str){
   int count = 0;
   for (int i=0; i<length; i++){
      if (str[i]==sub_str[0]){
         for (int j=i+1; j< length; j++){
            if(str[j]==sub_str[1]){
               for(int k=j+1; k<length; k++){
                  if(str[k]==sub_str[2])
                     { count++; }
               }
            }
         }
      }
   }
   return count;
}
int main(){
   string str = "TUTpoinTUTpoinTUT";
   int length = str.length();
   string sub_str = "TUT";
   cout<<"Count of subsequence of length three in a given string are: "<<subset_occurrence(str, length, sub_str);
   return 0;
}

Output

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

Count of subsequence of length three in a given string are: 19
raja
Published on 01-Dec-2020 12:17:32
Advertisements