Solution
Without using C++ string stream:
string toGoatLatin(string S) {
string res = "";
int wordCount = 1;
bool isVowel = false;
char firstChar;
for (int i=0; i<S.length();) {
if (S[i] == ' ') {
res+=" ";
wordCount++;
i++;
continue;
}
isVowel = isVowelFunc(S[i]);
firstChar = S[i];
if (isVowel)
res+=S[i];
i++;
while (i<S.length() && S[i] != ' ')
res+=S[i++];
if (!isVowel)
res+=firstChar;
res+="ma";
for (int j=0; j<wordCount; j++)
res+='a';
}
return res;
}
bool isVowelFunc (char c) {
c = tolower(c);
return c=='a' || c=='e' || c=='i' || c=='o' || c=='u';
}
Compact solution using C++ string stream:
string toGoatLatin(string S) {
unordered_set<char> vowel({'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'});
istringstream iss(S);
string res, w;
int i = 0, j;
while (iss >> w) {
res += ' ' + (vowel.count(w[0]) == 1 ? w : w.substr(1) + w[0]) + "ma";
for (j = 0, ++i; j < i; ++j) res += "a";
}
return res.substr(1);
}