Alternate vowel and consonant string in C/C++?

CC++Server Side ProgrammingProgramming

There is a string given, rearrange characters in the string such that the vowels and consonants occupy the alternate position. If string can’t be rearranged in the above manner, print “not possible”.

The order of vowels with respect to each other and the order of consonants with respect to each other should be maintained.

Input: abce
Output: abec

Explanation

  • Find the number of vowels and consonants in the string.

  • If the difference between no. of vowels and consonants are more than one, return “Not Possible”.

  • If there is a condition that more vowels are present in the string than consonants, print the first vowel first and recur for the remaining string.

  • If there is a condition that more consonants present in the string than vowels, print the first consonant first and recur for the remaining string.

  • If no. of vowels and consonants are same, compare the first vowel with the first consonant and print the smaller one first

Example

#include <iostream>
using namespace std;
bool isVowel(char ch) {
   if (ch == 'a' || ch == 'e' || ch == 'i' ||
      ch == 'o' || ch =='u')
   return true;
   return false;
}
string createAltStr(string str1, string str2,
int start, int l) {
   string finalStr = "";
   for (int i=0, j=start; j<l; i++, j++)
      finalStr = (finalStr + str1.at(i)) + str2.at(j);
   return finalStr;
}
string findAltStr(string str) {
   int nv = 0, nc = 0;
   string vstr = "", cstr = "";
   int l = str.size();
   for (int i=0; i<l; i++) {
      char ch = str.at(i);
      if (isVowel(ch)) {
         nv++;
         vstr = vstr + ch;
      } else {
         nc++;
         cstr = cstr + ch;
      }
   }
   if (abs(nv-nc) >= 2)
      return "no such string";
   if (nv > nc)
      return (vstr.at(0) + createAltStr(cstr, vstr, 1, nv));
   if (nc > nv)
      return (cstr.at(0) + createAltStr(vstr, cstr, 1, nc));
   if (cstr.at(0) < vstr.at(0))
      return createAltStr(cstr, vstr, 0, nv);
   return createAltStr(vstr, cstr, 0, nc);
}
int main() {
   string str = "abde";
   cout << findAltStr(str);
   return 0;
}
raja
Published on 20-Aug-2019 08:29:16
Advertisements