824. Goat Latin

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:

  • 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'.
  • 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".
  • 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. 


Example 1:

Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

Example 2:

Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"



  • S contains only uppercase, lowercase and spaces. Exactly one space between each word.
  • 1 <= S.length <= 150.

解题思路:将字符串分词,用到了istringstream 将字符串分词,判断这个词是否含有元音字母,用到了unordered_set存储元音字母(unordered_set不含重复元素),如果含有元音字母,将第一个字符放到最后。再加 ma,第一个词多加一个 a,第二个词多加两个 a
class Solution {
    string toGoatLatin(string S) {
        unordered_set<char> w({'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'});
        int count=0,i;
        istringstream iss(S);
        string res, c;
            res+=' '+ (w.count(c[0])==1?c:c.substr(1)+c[0]) + "ma";
            for(i=0, ++count ; i<count;i++)res+='a';
        return res.substr(1);

个人分类: LeetCode 字符串处理
想对作者说点什么? 我来说一句

matlab goat 工具箱的例子

2011年03月09日 30KB 下载



824. Goat Latin