ในกรณีของสตริงที่กำหนด ให้จัดเรียงอักขระของสตริงที่กำหนดใหม่เพื่อให้สระและพยัญชนะอยู่ในตำแหน่งอื่น หากไม่สามารถจัดเรียงสตริงใหม่ได้อย่างเหมาะสม ให้แสดง "ไม่มีสตริงดังกล่าว" ลำดับของสระที่สัมพันธ์กันและลำดับของพยัญชนะที่สัมพันธ์กันควรได้รับการสงวนรักษาไว้
หากสามารถสร้างสตริงที่จำเป็นได้มากกว่าหนึ่งรายการ ให้แสดงพจนานุกรมที่เล็กกว่า
ตัวอย่าง
Input : Tutorial Output : Tutorila Input : onse Output : 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
ความซับซ้อนของเวลา &ลบ O(n) โดยที่ 'n' ถือเป็นความยาวของสตริง