You are given a sentence sentence
that consists 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. That is, 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 sentence
to Goat Latin.
Input: sentence = "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
1 <= sentence.length <= 150
sentence
consists of English letters and spaces.def toGoatLatin(sentence: str) -> str:
def is_vowel(c):
return c.lower() in 'aeiou'
words = sentence.split()
goat_latin_sentence = []
for i, word in enumerate(words):
suffix = 'ma' + 'a' * (i + 1)
if is_vowel(word[0]):
goat_latin_word = word + suffix
else:
goat_latin_word = word[1:] + word[0] + suffix
goat_latin_sentence.append(goat_latin_word)
return ' '.join(goat_latin_sentence)
# Example usage:
sentence = "I speak Goat Latin"
print(toGoatLatin(sentence)) # Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Thus, the overall time complexity of the function is O(n), where n is the length of the input sentence, ensuring the approach is efficient for the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?