Input: sentence ="The quick brown fox jumped over the lazy dog"Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
We process each word in the sentence according to the Goat Latin rules: check if it starts with a vowel or consonant, transform accordingly, and add the right number of ‘a’s based on its position.
classSolution {
public String toGoatLatin(String sentence) {
String[] words = sentence.split(" ");
String vowels ="aeiouAEIOU";
StringBuilder ans =new StringBuilder();
for (int i = 0; i < words.length; i++) {
String w = words[i];
if (vowels.indexOf(w.charAt(0)) !=-1) {
w +="ma";
} else {
w = w.substring(1) + w.charAt(0) +"ma";
}
w +="a".repeat(i + 1);
ans.append(w);
if (i < words.length- 1) ans.append(' ');
}
return ans.toString();
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funtoGoatLatin(sentence: String): String {
val vowels = "aeiouAEIOU"return sentence.split(" ").mapIndexed { i, w ->val s = if (w[0] in vowels) w + "ma"else w.drop(1) + w[0] + "ma" s + "a".repeat(i + 1)
}.joinToString(" ")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
deftoGoatLatin(self, sentence: str) -> str:
vowels = set('aeiouAEIOU')
words = sentence.split()
ans = []
for i, w in enumerate(words):
if w[0] in vowels:
nw = w +'ma'else:
nw = w[1:] + w[0] +'ma' nw +='a'* (i +1)
ans.append(nw)
return' '.join(ans)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnto_goat_latin(sentence: String) -> String {
let vowels ="aeiouAEIOU";
sentence.split_whitespace().enumerate().map(|(i, w)| {
letmut s =if vowels.contains(w.chars().next().unwrap()) {
format!("{}ma", w)
} else {
letmut chs = w.chars();
let first = chs.next().unwrap();
format!("{}{}ma", chs.collect::<String>(), first)
};
s.push_str(&"a".repeat(i +1));
s
}).collect::<Vec<_>>().join(" ")
}
}