目录
1. 问题描述
给你一个由若干单词组成的句子 sentence ,单词间由空格分隔。每个单词仅由大写和小写英文字母组成。请你将句子转换为 “山羊拉丁文(Goat Latin)”(一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。山羊拉丁文的规则如下:
- 如果单词以元音开头('a','e','i','o','u'),在单词后添加"ma"。- 例如,单词 "apple"变为"applema"。
 
- 例如,单词 
- 如果单词以辅音字母开头(即,非元音字母),移除第一个字符并将它放到末尾,之后再添加"ma"。- 例如,单词 "goat"变为"oatgma"。
 
- 例如,单词 
- 根据单词在句子中的索引,在单词最后添加与索引相同数量的字母'a',索引从1开始。- 例如,在第一个单词后添加 "a",在第二个单词后添加"aa",以此类推。
 
- 例如,在第一个单词后添加 
返回将 sentence 转换为山羊拉丁文后的句子。
示例 1:
输入:sentence = "I speak Goat Latin" 输出:"Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
示例 2:
输入:sentence = "The quick brown fox jumped over the lazy dog" 输出:"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
提示:
- 1 <= sentence.length <= 150
- sentence由英文字母和空格组成
- sentence不含前导或尾随空格
- sentence中的所有单词由单个空格分隔
2. 解题分析
傻傻地遍历就是了。
对每个单词进行首字母判断,然后相应地进行字符串修改操作(可能的操作包括删除首位字符、末尾添加“m”或者“ma”、末尾添加若干个“a”)生成新的字符串。
当然,首先需要从sentence中提取出各个单词。单词间的空格一般情况下是一个,但是本题解放宽一些限制,单词间允许多个空格的出现,采用基于一个简易状态机的机制来实现。该状态机状态转移图如下所示:

以下代码虽然并没有显式地实现这个状态机,但是表达的意思的是相同的。
3. 代码实现
class Solution:
    def toGoatLatin(self, sentence: str) -> str:
        flag = False
        wordCnt = 0
        new_sentence = ''
        sentence = sentence + ' ' # for the convenience of the handle of the last word
        for k in range(len(sentence)):
            if sentence[k] != " " and not flag:
                flag = True
                start = k
            elif flag and sentence[k]==" ":
                # New word found
                word = sentence[start:k]
                wordCnt += 1
                flag = False
                if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:
                    new_sentence = new_sentence + word + 'ma' + wordCnt * 'a' + ' '
                else:
                    new_sentence = new_sentence + word[1:] + word[0] + 'ma' + wordCnt * 'a'+ ' '    
        return new_sentence[:-1] # Remove the last space执行用时:32 ms, 在所有 Python3 提交中击败了90.13%的用户
内存消耗:15.2 MB, 在所有 Python3 提交中击败了5.33%的用户
回到主目录:笨牛慢耕的Leetcode每日一解总目录(动态更新。。。)










