Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

จัดเรียงสระและพยัญชนะสลับกันใน C/C++

จัดเรียงสตริงให้สระและพยัญชนะสลับกัน ต้องมีจำนวนสระและพยัญชนะเท่ากันหรือต่างกันสูงสุด 1

เงื่อนไข

  • จำนวนสระ = จำนวนพยัญชนะ → เริ่มต้นได้ทั้งคู่
  • สระมากกว่า 1 → ต้องเริ่มด้วยสระ
  • พยัญชนะมากกว่า 1 → ต้องเริ่มด้วยพยัญชนะ

ตัวอย่าง

"individual" (5v,5c) → "inidivudal"
"noe" (2v,1c) → "one"
"objective" (4v,5c) → "bojecitev"

อัลกอริทึม

  1. นับสระ/พยัญชนะ แยกเก็บใน string แยกกัน
  2. ตรวจสอบเงื่อนไขความต่าง ≤ 1
  3. รวมสลับกันตามจำนวน

โค้ด C++ ตัวอย่าง

#include <iostream>
#include <string>
using namespace std;

bool is_vowel(char c) {
    return c=='a'||c=='e'||c=='i'||c=='o'||c=='u';
}

string alternate(string s) {
    string v, c;
    for (char ch : s) (is_vowel(ch) ? v : c) += ch;
    if (abs((int)v.size() - (int)c.size()) > 1) return "Impossible";

    string res;
    if (v.size() >= c.size()) {
        for (int i = 0; i < c.size(); i++) res += v[i], res += c[i];
        if (v.size() > c.size()) res += v.back();
    } else {
        for (int i = 0; i < v.size(); i++) res += c[i], res += v[i];
        res += c.back();
    }
    return res;
}

int main() {
    cout << alternate("individual") << endl; // inidivudal
    cout << alternate("noe") << endl;        // one
    cout << alternate("objective") << endl;  // bojecitev
    return 0;
}