Count substrings that starts with character X and ends with character Y in C++


We are given string str. The goal is to count the number of substrings in str that have starting character same as character X and ending character same as character Y. For example, if input is “artact” and X=’a’ and Y=’t’, the substrings will be “art”, “act”, “artact”. The count is 3.

Let us understand with examples.

Input − str=”abcccdef” X=’a’ Y=’c’

Output −Count of substrings that starts with character X and ends with Y is − 3

Explanation − Substrings will be

“abc”, “abcc”, “abccc”. Total 3.

Input − str=”tempest” X=’t’ Y=’t’

Output − Count of substrings that starts with character X and ends with Y are − 3

Explanation − Substrings will be −

“t” , “tempest” , “t”. Total 3

The approach used in the below program is as follows

We will traverse the string and increment count of X. If then Y is encountered add X count to the count of strings that start with X and end with Y.

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

  • Function X_Y(string str, int length, char X, char Y) takes string str, characters X, Y and returns the count of substrings of str that start with X and end with Y.

  • Take the initial count as 0.

  • Take x_total as count of character X in str.

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

  • If str[i]==X, increment count of X’s in str (x_total++).

  • If str[i]==Y, add x_total to count. If no X was there x_total would be 0, otherwise, Y is the end character of the substring that started from X.

  • Return count as the desired result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int X_Y(string str, int length, char X, char Y){
   int count = 0;
   int x_total = 0;
   for (int i = 0; i < length; i++){
      if(str[i] == X){
         x_total++;
      }
      if (str[i] == Y){
         count = count + x_total;
      }
   }
   return count;
}
int main(){
   string str = "defaabbcchhkl";
   int length = str.size();
   char X = 'd';
   char Y = 'a';
   cout<<"Count of substrings that starts with character X and ends with character Y are: "<<X_Y(str, length, X, Y);
   return 0;
}

Output

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

Count of substrings that starts with character X and ends with character Y are: 2

Updated on: 01-Dec-2020

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements