↓快轉到主要內容
  1. LeetCode/

LeetCode 824: Goat Latin

·1 分鐘· ·
LeetCode Easy String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-09-15

  • 提交紀錄:Accepted ×2

解題思路
#

切成單字後逐一處理(String 模板六):開頭是母音(大小寫都算)就不動,否則把第一個字母移到最後;接著加上 "ma",再加上 i + 1 個 "a"(i 是單字的 index,從 0 開始)。

我的解法
#

class Solution:
    def toGoatLatin(self, sentence: str) -> str:
        res = []
        for i, w in enumerate(sentence.split()):
            if w[0] not in "aeiouAEIOU":
                w = w[1:] + w[0]
            res.append(w + "ma" + "a" * (i + 1))
        return " ".join(res)

複雜度
#

時間 O(n + w²)(w 是單字數,加上的 a 總共 O(w²) 個),空間同上。

要特別避免的錯誤
#

  • 母音包含大寫。
  • 第一個單字加 1 個 a,不是 0 個。

面試口說整理
#

我把句子切成單字,子音開頭的把第一個字母移到最後,每個單字加上 ma 和 index 加一個 a,最後用空白接起來。

相關文章

LeetCode 804: Unique Morse Code Words
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 804 解題筆記:把每個單字轉成摩斯碼字串,放進集合後算有幾種
LeetCode 657: Robot Return to Origin
·1 分鐘
LeetCode Easy String Simulation
LeetCode 657 解題筆記:回到原點等價於上下次數相同、左右次數相同
LeetCode 557: Reverse Words in a String III
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 557 解題筆記:用空白切開,每個單字各自反轉,再用空白接回去
LeetCode 500: Keyboard Row
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 500 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留
LeetCode 520: Detect Capital
·1 分鐘
LeetCode Easy String
LeetCode 520 解題筆記:合法的只有三種:全大寫、全小寫、只有第一個字母大寫
LeetCode 521: Longest Uncommon Subsequence I
·1 分鐘
LeetCode Easy String
LeetCode 521 解題筆記:兩個字串相同時答案是 -1,否則比較長的那個整個就是答案