 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements
 