Print all Subsequences of String which Start with Vowel and End with Consonant in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string and we have to find the substring from the given string. The substring to be found should start with a vowel and end with constant character.

A string is an array of characters.

The substring that is to be generated in this problem can be generated by deleting some characters of the string. And without changing the order of the string.

Input: ‘abc’
Output: ab, ac, abc

To solve this problem, we will iterate the string and fix vowels and check for the next sequence. Let’s see an algorithm to find a solution −

Algorithm

Step 1: Iterate of each character of the string, with variable i.
Step 2: If the ith character is a vowel.
Step 3: If the jth character is a consonant.
Step 4: Add to the HashSet, substring from 1st character to jth character.
Step 5: Repeat the following steps and find substrings from the string.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
set<string> st;
bool isaVowel(char c);
bool isaConsonant(char c);
void findSubSequence(string str);
int main(){
   string s = "abekns";
   findSubSequence(s);
   cout<<"The substring generated are :\n";
   for (auto i : st)
      cout<<i<<" ";
   cout << endl;
   return 0;
}
bool isaVowel(char c) {
   return (c=='a'||c=='e'||c=='i'||c=='o'||c=='u');
}
bool isaConsonant(char c) {
   return !isaVowel(c);
}
void findSubSequence(string str) {
   for (int i = 0; i < str.length(); i++) {
      if (isaVowel(str[i])) {
         for (int j = str.length() - 1; j >= i; j--) {
            if (isaConsonant(str[j])) {
               string str_sub = str.substr(i, j + 1);
               st.insert(str_sub);
               for (int k = 1; k < str_sub.length() - 1; k++){
                  string sb = str_sub;
                  sb.erase(sb.begin() + k);
                  findSubSequence(sb);
               }
            }
         }
      }
   }
}

Output

The substring generated are −

ab abek abekn abekns abeks aben abens abes abk abkn abkns abks abn abns abs aek aekn aekns aeks aen aens aes ak akn akns aks an ans as ek ekn ekns eks en ens es
raja
Published on 17-Jan-2020 10:44:00
Advertisements