C++中交替出现元音和辅音的字符串
对于给定的字符串,重新排列字符,使得元音和辅音交替出现。如果字符串无法以正确的方式重新排列,则显示“无此字符串”。元音之间的顺序和辅音之间的顺序应保持不变。
如果可以构造多个所需的字符串,则显示字典序较小的字符串。
示例
Input : Tutorial Output : Tutorila Input : onse Output : nose
存在两种可能的输出“nose”和“ones”。由于“nose”在字典序中较小,因此我们显示它。
计算给定字符串中元音和辅音的数量。
在这种情况下,如果计数之间的差大于一,则返回“不可能”。
在这种情况下,如果元音多于辅音,则先显示第一个元音,然后对剩余字符串进行递归。
在这种情况下,如果辅音多于元音,则先显示第一个辅音,然后对剩余字符串进行递归。
在这种情况下,如果计数相同,则比较第一个元音和第一个辅音,先显示较小的一个。
示例
// C++ application of alternate vowel and consonant string
#include <bits/stdc++.h>
using namespace std;
// 'ch1' is treated as vowel or not
bool isVowel(char ch1){
if (ch1 == 'a' || ch1 == 'e' || ch1 == 'i' ||
ch1 == 'o' || ch1 =='u')
return true;
return false;
}
// build alternate vowel and consonant string
// str1[0...l2-1] and str2[start...l3-1]
string createAltStr(string str1, string str2,
int start1, int l1){
string finalStr1 = "";
// first adding character of vowel/consonant
// then adding character of consonant/vowel
for (int i=0, j=start1; j<l1; i++, j++)
finalStr1 = (finalStr1 + str1.at(i)) + str2.at(j);
return finalStr1;
}
// function to locate or find the needed alternate vowel and consonant string
string findAltStr(string str3){
int nv1 = 0, nc1 = 0;
string vstr1 = "", cstr1 = "";
int l1 = str3.size();
for (int i=0; i<l1; i++){
char ch1 = str3.at(i);
// count vowels and updaye vowel string
if (isVowel(ch1)){
nv1++;
vstr1 = vstr1 + ch1;
}
// counting consonants and updating consonant string
else{
nc1++;
cstr1 = cstr1 + ch1;
}
}
// no such string can be built
if (abs(nv1-nc1) >= 2)
return "no such string";
// delete first character of vowel string
// then built alternate string with
// cstr1[0...nc1-1] and vstr1[1...nv1-1]
if (nv1 > nc1)
return (vstr1.at(0) + createAltStr(cstr1, vstr1, 1, nv1));
// delete first character of consonant string
// then built alternate string with
// vstr1[0...nv1-1] and cstr1[1...nc1-1]
if (nc1 > nv1)
return (cstr1.at(0) + createAltStr(vstr1, cstr1, 1, nc1));
// if both vowel and consonant
// strings are of equal length
// start building string with consonant
if (cstr1.at(0) < vstr1.at(0))
return createAltStr(cstr1, vstr1, 0, nv1);
// start building string with vowel
return createAltStr(vstr1, cstr1, 0, nc1);
}
// Driver program to test above
int main(){
string str3 = "Tutorial";
cout<< findAltStr(str3);
return 0;
}输出
Tutorila
时间复杂度 &minus O(n),其中‘n’表示字符串的长度
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP