|
| 1 | +import java.util.Set; |
| 2 | + |
| 3 | +public class GoatLatin { |
| 4 | + private static final Set<Character> VOWELS = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'); |
| 5 | + |
| 6 | + public String toGoatLatin(String sentence) { |
| 7 | + StringBuilder result = new StringBuilder(), word = new StringBuilder(); |
| 8 | + char firstLetter = ' '; |
| 9 | + int wordCount = 1; |
| 10 | + boolean vowelWord = false, newWord = true; |
| 11 | + for (int index = 0 ; index < sentence.length() ; index++) { |
| 12 | + if (newWord) { |
| 13 | + if (index == sentence.length() - 1) { |
| 14 | + result.append(toGoatLatin(wordCount, new StringBuilder(), |
| 15 | + false, sentence.charAt(index))); |
| 16 | + break; |
| 17 | + } |
| 18 | + if (isVowel(sentence.charAt(index))) { |
| 19 | + vowelWord = true; |
| 20 | + word.append(sentence.charAt(index)); |
| 21 | + } else { |
| 22 | + vowelWord = false; |
| 23 | + firstLetter = sentence.charAt(index); |
| 24 | + } |
| 25 | + |
| 26 | + newWord = false; |
| 27 | + } else if (sentence.charAt(index) == ' ' || index == sentence.length() - 1) { |
| 28 | + newWord = true; |
| 29 | + if (index == sentence.length() - 1) word.append(sentence.charAt(index)); |
| 30 | + result.append(toGoatLatin(wordCount, word, vowelWord, firstLetter)); |
| 31 | + word = new StringBuilder(); |
| 32 | + wordCount++; |
| 33 | + } else { |
| 34 | + word.append(sentence.charAt(index)); |
| 35 | + } |
| 36 | + } |
| 37 | + return result.toString(); |
| 38 | + } |
| 39 | + |
| 40 | + private StringBuilder toGoatLatin(int wordCount, StringBuilder word, boolean vowelWord, char firstLetter) { |
| 41 | + return new StringBuilder() |
| 42 | + .append(wordCount == 1 ? "" : ' ') |
| 43 | + .append(word) |
| 44 | + .append(vowelWord ? "" : firstLetter) |
| 45 | + .append("ma") |
| 46 | + .append("a".repeat(wordCount)); |
| 47 | + } |
| 48 | + |
| 49 | + private boolean isVowel(char character) { |
| 50 | + return VOWELS.contains(character); |
| 51 | + } |
| 52 | +} |
0 commit comments