描述:A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to “Goat Latin” (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
1. If a word begins with a vowel (a, e, i, o, or u), append “ma” to the end of the word.
For example, the word ‘apple’ becomes ‘applema’.
2. If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add “ma”.
For example, the word “goat” becomes “oatgma”.
3. Add one letter ‘a’ to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets “a” added to the end, the second word gets “aa” added to the end and so on.
Return the final sentence representing the conversion from S to Goat Latin.分析:这道题是要求按照一定规则实现一个字符串替换算法,和Pig Latin类似,题目中要求有三点:
1.如果遇到原音字母开头单词(a,e,i,o,u)则保留这个单词,并在这个单词末尾添加”ma”字符串
2.如果遇到非原音字母开头的单词,将首字母移动到单词尾部,然后在尾部添加”ma”
3.对于每个单词,在单词末尾添加额外的”a…”字符串,其中a的数目由单词出现的数目决定思路一:这道题其实主要问题在于每个单词分隔位置的判断,我在这里采用的是检测空格的位置,用一个bool变量来记录字符串的分隔情况,分隔处理完成之后就十分简单了。
class Solution {
public:
string toGoatLatin(string S) {
string res = "";
string rear = "a";
bool state_flag = true;
string add_str = "";
for (int i = 0; i < S.size(); i++) {
res += S[i];
if (state_flag) {
if (S[i] == 'A' || S[i] == 'E' || S[i] == 'I' || S[i] == 'O' || S[i] == 'U' || S[i] == 'a' || S[i] == 'e' || S[i] == 'i' || S[i] == 'o' || S[i] == 'u') {
add_str = "";
} else {
add_str = S[i];
res.pop_back();
}
state_flag = false;
}
if (S[i] == ' ' || i == S.size() - 1) {
state_flag = true;
add_str += "ma";
add_str += rear;
if (S[i] == ' ') res.insert(res.size() - 1, add_str);
else res.insert(res.size(), add_str);
rear += 'a';
}
}
return res;
}
};