Home > Article > Backend Development > 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
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.
#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; }
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!