LeetCode 题解工作台
山羊拉丁文
给你一个由若干单词组成的句子 sentence ,单词间由空格分隔。每个单词仅由大写和小写英文字母组成。 请你将句子转换为 “ 山羊拉丁文( Goat Latin ) ” (一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。山羊拉丁文的规则如下: 如果单词以元音开头( 'a' , 'e' …
1
题型
4
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
class Solution: def toGoatLatin(self, sentence: str) -> str:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个由若干单词组成的句子 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 <= 150sentence由英文字母和空格组成sentence不含前导或尾随空格sentence中的所有单词由单个空格分隔
解题思路
方法一
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.