มีสตริงที่กำหนด จัดเรียงอักขระใหม่ในสตริงเพื่อให้สระและพยัญชนะอยู่ในตำแหน่งอื่น หากไม่สามารถจัดเรียงสตริงใหม่ในลักษณะข้างต้นได้ ให้พิมพ์ "ไม่สามารถทำได้"
ควรรักษาลำดับของสระที่สัมพันธ์กันและลำดับของพยัญชนะที่สัมพันธ์กัน
Input: abce Output: abec
คำอธิบาย
-
หาจำนวนสระและพยัญชนะในสตริง
-
หากความแตกต่างระหว่างหมายเลข สระและพยัญชนะมากกว่า 1 ตัว ให้คืนค่าว่า "เป็นไปไม่ได้"
-
หากมีเงื่อนไขว่าในสตริงมีสระมากกว่าพยัญชนะ ให้พิมพ์สระแรกก่อนและทำซ้ำสำหรับสตริงที่เหลือ
-
หากมีเงื่อนไขว่ามีพยัญชนะในสตริงมากกว่าสระ ให้พิมพ์พยัญชนะตัวแรกก่อนและทำซ้ำสำหรับสตริงที่เหลือ
-
ถ้าไม่. สระและพยัญชนะเหมือนกัน เปรียบเทียบสระแรกกับพยัญชนะตัวแรก แล้วพิมพ์ตัวที่เล็กกว่าก่อน
ตัวอย่าง
#include <iostream>
using namespace std;
bool isVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch =='u')
return true;
return false;
}
string createAltStr(string str1, string str2,
int start, int l) {
string finalStr = "";
for (int i=0, j=start; j<l; i++, j++)
finalStr = (finalStr + str1.at(i)) + str2.at(j);
return finalStr;
}
string findAltStr(string str) {
int nv = 0, nc = 0;
string vstr = "", cstr = "";
int l = str.size();
for (int i=0; i<l; i++) {
char ch = str.at(i);
if (isVowel(ch)) {
nv++;
vstr = vstr + ch;
} else {
nc++;
cstr = cstr + ch;
}
}
if (abs(nv-nc) >= 2)
return "no such string";
if (nv > nc)
return (vstr.at(0) + createAltStr(cstr, vstr, 1, nv));
if (nc > nv)
return (cstr.at(0) + createAltStr(vstr, cstr, 1, nc));
if (cstr.at(0) < vstr.at(0))
return createAltStr(cstr, vstr, 0, nv);
return createAltStr(vstr, cstr, 0, nc);
}
int main() {
string str = "abde";
cout << findAltStr(str);
return 0;
}