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

Alternating vowel and consonant strings in C/C++

PHPz
Release: 2023-08-27 08:45:28
forward
888 people have browsed it

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
Copy after login

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;
}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template