Split the sentence, move an initial consonant when needed, append the fixed suffix, then add one more 'a' per word position.
Complexity
O(n) time and O(n) output space.
Transform every word in a sentence according to the Goat Latin rules.
Split the sentence, move an initial consonant when needed, append the fixed suffix, then add one more 'a' per word position.
O(n) time and O(n) output space.
package main
import "strings"
func toGoatLatin(sentence string) string {
vowels := "aeiouAEIOU"
words := strings.Fields(sentence)
for index, word := range words {
if !strings.ContainsRune(vowels, rune(word[0])) {
word = word[1:] + word[:1]
}
words[index] = word + "ma" + strings.Repeat("a", index+1)
}
return strings.Join(words, " ")
}
class Solution:
def toGoatLatin(self, sentence: str) -> str:
vowels = set("aeiouAEIOU")
result: list[str] = []
for index, word in enumerate(sentence.split(), 1):
base = word if word[0] in vowels else word[1:] + word[0]
result.append(base + "ma" + "a" * index)
return " ".join(result)
function toGoatLatin(sentence: string): string {
const vowels = new Set("aeiouAEIOU");
return sentence.split(" ").map((word, index) => {
const base = vowels.has(word[0]) ? word : word.slice(1) + word[0];
return base + "ma" + "a".repeat(index + 1);
}).join(" ");
}