LeetCode 824 Goat Latin 解题报告

时间:2021-11-17 04:01:10

题目要求

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.

题目分析及思路

给定一个句子,其中只包含word和space,word只由大小写字母组成。先将这个句子进行转换,转换规则如下:

  1)若一个word以元音字母开头,则在这个word末尾添加'ma'

  2)若一个word以辅音字母开头,则将这个word开头字母移到末尾,并在这个word末尾添加'ma'

  3)对句中的每一个word,根据它的索引在word末尾添加'a'。若索引为0,则添加一个'a',为1则添加两个'a',以此类推

最后将转换好的句子返回。

python代码

class Solution:

def toGoatLatin(self, S: str) -> str:

S = S.split()

s_gls = ''

for idx, s in enumerate(S):

if s[0] in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']:

s_gl = s + 'ma'

else:

s_gl = s[1:] + s[0] + 'ma'

s_gl += (idx+1)*'a'

s_gls += s_gl + ' '

return s_gls.strip()