Find the count of substrings in alphabetic order in C++


Suppose we have a string of length n. It contains only uppercase letters. We have to find the number of substrings whose character is occurring in alphabetical order. Minimum size of the substring will be 2. So if the string is like: “REFJHLMNBV”, and substring count is 2, they are “EF” and “MN”.

So to solve this, we will follow these steps −

  • Check whether str[i] + 1 is same as the str[i+1], if so, then increase the result by 1, and iterate the string till next character which is out of alphabetic order, otherwise continue.

Example

 Live Demo

#include<iostream>
using namespace std;
int countSubstr(string main_str) {
   int res = 0;
   int n = main_str.size();
   for (int i = 0; i < n - 1; i++) {
      if (main_str[i] + 1 == main_str[i + 1]) {
         res++;
         while (main_str[i] + 1 == main_str[i + 1]) {
            i++;
         }
      }
   }
   return res;
}
int main() {
   string str = "REFJHLMNBV";
   cout << "Number of substrings: " << countSubstr(str);
}

Output

Number of substrings: 2

Updated on: 19-Dec-2019

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements