题目如下:
点此读题
给定一个由空格分割单词的句子 S。每个单词只包含大写或小写字母。
我们要将句子转换为 “Goat Latin”(一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。
山羊拉丁文的规则如下:
如果单词以元音开头(a, e, i, o, u),在单词后添加"ma"。
例如,单词"apple"变为"applema"。
如果单词以辅音字母开头(即非元音字母),移除第一个字符并将它放到末尾,之后再添加"ma"。
例如,单词"goat"变为"oatgma"。
根据单词在句子中的索引,在单词最后添加与索引相同数量的字母’a’,索引从1开始。
例如,在第一个单词后添加"a",在第二个单词后添加"aa",以此类推。
返回将 S 转换为山羊拉丁文后的句子。
示例 1:
输入: “I speak Goat Latin”
输出: “Imaa peaksmaaa oatGmaaaa atinLmaaaaa”
示例 2:
输入: “The quick brown fox jumped over the lazy dog”
输出: “heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa”
说明:
S 中仅包含大小写字母和空格。单词间有且仅有一个空格。
1 <= S.length <= 150。
题目还算浅显易懂,思路一看也能够清晰理顺。首先以split空格分割字符串,判断每个单词首字母是否为元,是将其移至末尾。根据单词的位置,在以上基础的单词上分别添加ma和n个a,将修改完的单词重新以空格为间隔拼接为字符串。按部就班来即可
代码如下:
class Solution {
public:
vector<string> split(const string& str, const string& pattern)
{
vector<string> ret;
if (pattern.empty()) return ret;
size_t start = 0, index = str.find_first_of(pattern, 0);
while (index != str.npos)
{
if (start != index)
ret.push_back(str.substr(start, index - start));
start = index + 1;
index = str.find_first_of(pattern, start);
}
if (!str.substr(start).empty())
ret.push_back(str.substr(start));
return ret;
}
string toGoatLatin(string S)
{
string res;
vector<string> Words = split(S, " ");
for (int i = 0; i < Words.size(); i++)
{
if (Words[i][0] != 'a' && Words[i][0] != 'e' && Words[i][0] != 'i' && Words[i][0] != 'o' && Words[i][0] != 'u' &&
Words[i][0] != 'A' && Words[i][0] != 'E' && Words[i][0] != 'I' && Words[i][0] != 'O' && Words[i][0] != 'U')
{
for (int j = 0; j < Words[i].size()-1; j++)
{
char temp = Words[i][j];
Words[i][j] = Words[i][j+1];
Words[i][j+1] = temp;
}
}
string EndStr="ma";
for (int j = 0; j <= i; j++)
{
EndStr += "a";
}
Words[i] += EndStr;
res += Words[i];
if (i != Words.size() - 1)res += " ";
}
return res;
}
写的繁琐了一点,胜在能运行