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’表示字串的長度

更新於: 2020年1月29日

160 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告