C/C++ 中的母音和子音交替出現的字串


給定一個包含母音和子音的輸入字串,重新排列字串,使得母音和子音在最終字串中交替出現。由於我們正在交替排列母音和子音,因此輸入字串必須滿足以下條件之一 -

  • 母音和子音的數量必須相同,例如字串“individual”有 5 個母音和 5 個子音。

  • 如果母音的數量多,那麼母音數量和子音數量之間的差必須為 1,例如字串“noe”有 2 個母音和 1 個子音。

  • 如果子音數量多,那麼子音數量和母音數量之間的差必須為 1,例如字串“objective”有 4 個母音和 5 個子音。

演算法

1. count number of vowels
2. Count number of consonants
3. if difference between number of vowels and consonants or viceversa is greater than 1 then return error
4. Split input string into two parts:
   a) First string contains only vowels
   b) Second string contains only consonants
5. If number of consonants and vowels are equal, then create final string by picking a character from each string alternatively.
6. If number of vowels are greater than consonants, then:
   a) Include additional vowel in final string to make both strings of equal length
   b) Create final string by appending a character from each string alternatively
7. If number of consonants are greater than vowels, then
   a) Include additional consonant in final string to make both strings of equal length
   b) Create final string by appending a character from each string alternatively

示例

 線上演示

#include <iostream>
#include <string>
using namespace std;
bool is_vowel(char ch) {
   if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') {
      return true;
   }
   return false;
}
string create_final_string(string &s1, string &s2, int start, int end) {
   string final_string;
   for (int i = 0, j = start; j < end; ++i, ++j) {
      final_string = (final_string + s1.at(i)) + s2.at(j);
   }
   return final_string;
}
string create_alternate_string(string &s) {
   int vowel_cnt, consonant_cnt;
   string vowel_str, consonant_str;
   vowel_cnt = consonant_cnt = 0;
   for (char c : s) {
      if (is_vowel(c)) {
         ++vowel_cnt;
         vowel_str += c;
      } else {
         ++consonant_cnt;
         consonant_str += c;
      }
   }
   if (abs(consonant_cnt - vowel_cnt) >= 2) {
      cerr << "String cannot be formed with alternating vowels and cosonants\n";
      exit(1);
   }
   if ((consonant_cnt - vowel_cnt) == 0) {
      return create_final_string(vowel_str, consonant_str, 0, vowel_cnt);
   } else if (vowel_cnt > consonant_cnt) {
      return vowel_str.at(0) + create_final_string(consonant_str,vowel_str, 1, vowel_cnt);
   }
   return consonant_str.at(0) + create_final_string(vowel_str,consonant_str, 1, consonant_cnt);
}
int main() {
   string s1 = "individual";
   string s2 = "noe";
   string s3 = "objective";
   cout << "Input : " << s1 << "\n";
   cout << "Output: " << create_alternate_string(s1) << "\n\n";
   cout << "Input : " << s2 << "\n";
   cout << "Output: " << create_alternate_string(s2) << "\n\n";
   cout << "Input : " << s3 << "\n";
   cout << "Output: " << create_alternate_string(s3) << "\n\n";
}

輸出

當你編譯並執行以上程式碼時,它將生成以下輸出 -

Input : individual
Output: inidivudal
Input : noe
Output: one
Input : objective
Output: bojecitev

更新於: 2019-9-26

310 瀏覽量

開啟你的職業生涯

完成課程並獲得認證

開始學習
廣告