LeetCode 题解工作台

山羊拉丁文

给你一个由若干单词组成的句子 sentence ,单词间由空格分隔。每个单词仅由大写和小写英文字母组成。 请你将句子转换为 “ 山羊拉丁文( Goat Latin ) ” (一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。山羊拉丁文的规则如下: 如果单词以元音开头( 'a' , 'e' …

category

1

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

class Solution: def toGoatLatin(self, sentence: str) -> str:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由若干单词组成的句子 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 中的所有单词由单个空格分隔
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def toGoatLatin(self, sentence: str) -> str:
        ans = []
        for i, word in enumerate(sentence.split()):
            if word.lower()[0] not in ['a', 'e', 'i', 'o', 'u']:
                word = word[1:] + word[0]
            word += 'ma'
            word += 'a' * (i + 1)
            ans.append(word)
        return ' '.join(ans)
speed

复杂度分析

指标
时间complexity is O(n) where n is the total number of characters, because each character is processed once during word transformation. Space complexity is O(n) due to splitting the sentence and storing transformed words.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect clear handling of vowels versus consonants in string transformations.

  • question_mark

    Pay attention to appending the correct number of 'a's per word index.

  • question_mark

    Ensure capitalization and spacing are preserved exactly as input.

warning

常见陷阱

外企场景
  • error

    Forgetting to append incremental 'a's according to word position.

  • error

    Misclassifying uppercase vowels or consonants due to case sensitivity.

  • error

    Incorrectly joining words and adding extra or missing spaces.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify rules to add different suffixes per word index instead of 'a's.

  • arrow_right_alt

    Handle sentences with punctuation interspersed between words.

  • arrow_right_alt

    Apply Goat Latin rules to multilingual strings with accented characters.

help

常见问题

外企场景

山羊拉丁文题解:String-driven solution … | LeetCode #824 简单