The problem is to transform a sentence into Goat Latin. A sentence consists of words separated by spaces. Each word consists of lowercase and uppercase letters only.
Rules of Goat Latin:
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. For example, the first word gets “a” added to the end, the second word gets “aa” added, and so on.
Return the final sentence representing the conversion to Goat Latin.
public class GoatLatin {
public static String toGoatLatin(String sentence) {
// Base vowels set
Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
// Split the sentence into words
String[] words = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (vowels.contains(word.charAt(0))) {
sb.append(word);
} else {
sb.append(word.substring(1)).append(word.charAt(0));
}
sb.append("ma").append("a".repeat(i + 1));
if (i != words.length - 1) {
sb.append(" ");
}
}
return sb.toString();
}
// You can use the below main method for quick testing
public static void main(String[] args) {
String sentence = "I speak Goat Latin";
System.out.println(toGoatLatin(sentence)); // Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
}
}
This approach ensures that we efficiently transform the given sentence to Goat Latin following the specified rules.
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?