주어진 문자열의 경우 모음과 자음이 다른 위치를 차지하도록 문자열의 문자를 재배열합니다. 문자열을 올바른 방법으로 재배열할 수 없는 경우 "해당 문자열 없음"을 표시합니다. 모음의 순서와 자음의 순서는 잘 지켜져야 합니다.
필요한 문자열을 두 개 이상 구성할 수 있는 경우 사전순으로 더 작게 표시합니다.
예시
Input : Tutorial Output : Tutorila Input : onse Output : nose
"코"와 "하나"의 두 가지 가능한 결과가 있습니다. "nose"는 사전순으로 더 작기 때문에 표시합니다.
-
주어진 문자열의 모음과 자음의 개수를 셉니다.
-
이 경우 개수의 차이가 1 이상인 경우 "불가능"을 반환합니다.
-
이 경우 모음이 자음보다 많을 경우 첫 번째 모음을 먼저 표시하고 나머지 문자열에 대해 반복됩니다.
-
이 경우 모음보다 자음이 많을 경우 첫 번째 자음을 먼저 표시하고 나머지 문자열에 대해 반복됩니다.
-
이 경우 개수가 같으면 첫 번째 모음을 첫 번째 자음과 비교하여 작은 쪽부터 먼저 표시합니다.
예시
// 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'은 문자열의 길이로 처리됩니다.