1. 程式人生 > 其它 >【字串-簡單】824. 山羊拉丁文

【字串-簡單】824. 山羊拉丁文

技術標籤:# leetcodepython字串leetcode

題目
給定一個由空格分割單詞的句子 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。
【程式碼】
【Python】
時間複雜度和空間複雜度略高
執行用時:
48 ms, 在所有 Python3 提交中擊敗了11.08%的使用者
記憶體消耗:
14.9 MB, 在所有 Python3 提交中擊敗了5.20%的使用者

class Solution:
    def toGoatLatin(self, S: str) -> str:
        words=S.split(" ")
        muban="aAeEiIoOuU"
cnt=0 for word in words: cnt+=1 #以母音字母開頭 在結尾加 ma 和序號個a if muban.find(word[0])!=-1: word+="ma"+"a"*cnt else: word=word[1:]+word[:1]+"ma"+"a"*cnt words[cnt-1]=word return " ".join(words)