Home >Backend Development >C++ >Alternating vowel and consonant strings in C/C++

Alternating vowel and consonant strings in C/C++

PHPz
PHPzforward
2023-08-27 08:45:28914browse

Alternating vowel and consonant strings in C/C++

Given a string, rearrange the characters in the string so that vowels and consonants occupy alternating positions. If the string cannot be rearranged as described above, print "impossible".

The order between vowels and the order between consonants should remain the same.

Input: abce
Output: abec

Explanation

  • Count the number of vowels and consonants in a string.

  • If the difference between the number of vowels and consonants exceeds 1, return "impossible".

  • If there are more vowels than consonants in the string, print the first vowel first and then recurse for the remaining strings.

  • If there are more consonants than vowels in the string, print the first consonant first and then recurse for the remaining strings.

  • If the number of vowels and consonants is the same, compare the first vowel and the first consonant and print the smaller one first.

Example

#include <iostream>
using namespace std;
bool isVowel(char ch) {
   if (ch == &#39;a&#39; || ch == &#39;e&#39; || ch == &#39;i&#39; ||
      ch == &#39;o&#39; || ch ==&#39;u&#39;)
   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;
}

The above is the detailed content of Alternating vowel and consonant strings in C/C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete