Goat Latin LeetCode solution in Java

1
class Solution {
2
public String toGoatLatin(String sentence) {
3
StringBuffer sb = new StringBuffer();
4
StringBuffer temp = new StringBuffer("a"); // temporary stringbuffer
5

6
for (String str : sentence.split(" ")) {
7
if (beginsWithConsonant(str)) {
8
sb.append(str.substring(1)); // removing the first letter
9
sb.append(str.charAt(0)); // appending it to the end
10
} else {
11
sb.append(str);
12
}
13

14
sb.append("ma"); // appending "ma" to the end of the word (common operation)
15
sb.append(temp); // adding one letter 'a' to the end of each word
16

17
// the first word gets "a" added to the end,
18
// the second word gets "aa" added to the end,
19
// and so on.
20
temp.append("a"); // increasing the a's for every word
21
sb.append(" "); // to put space between words
22
}
23

24
return sb.toString()
25
.trim(); // using trim() to remove the one extra space from the end of string.
26
}
27

28
public boolean beginsWithConsonant(String str) {
29
return "aeiou".indexOf(str.toLowerCase().charAt(0)) == -1;
30
}
31
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0