在 C/C++ 中交替元音和辅音

cc++server side programmingprogramming

给定一个包含元音和辅音的输入字符串。重新排列字符串,使元音和辅音在最终字符串中占据交替位置。由于我们将元音和辅音排列在交替位置,因此输入字符串必须满足以下任一条件 −

  • 元音和辅音的数量必须相同,例如字符串 "individual" 有 5 个元音和 5 个辅音。

  • 如果元音数量较多,则元音数量和辅音数量之间的差值必须为 1,例如字符串 "noe"有 2 个元音和 1 个辅音。

  • 如果辅音数量较多,则辅音数量与元音数量之差必须为 1,例如字符串"objective"有 4 个元音和 5 个辅音。

算法

1. 计算元音数量
2. 计算辅音数量
3. 如果元音和辅音数量之差或反之大于 1,则返回错误
4. 将输入字符串拆分为两部分:
   a) 第一个字符串仅包含元音
   b) 第二个字符串仅包含辅音
5. 如果辅音和元音数量相等,则通过从每个字符串中交替选择一个字符来创建最终字符串。
6. 如果元音的数量大于辅音的数量,则:
   a) 在最终字符串中包含额外的元音,使两个字符串的长度相等
   b) 通过交替地从每个字符串中附加一个字符来创建最终字符串
7. 如果辅音的数量大于元音的数量,则
   a) 在最终字符串中包含额外的辅音,使两个字符串的长度相等
   b) 通过交替地从每个字符串中附加一个字符来创建最终字符串

示例

#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

相关文章