|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.HashSet; |
| 5 | +import java.util.Set; |
| 6 | + |
| 7 | +/** |
| 8 | + * 824. Goat Latin |
| 9 | + * |
| 10 | + * A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only. |
| 11 | + * |
| 12 | + * We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) |
| 13 | + * |
| 14 | + * The rules of Goat Latin are as follows: |
| 15 | + * |
| 16 | + * If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of the word. |
| 17 | + * For example, the word 'apple' becomes 'applema'. |
| 18 | + * |
| 19 | + * 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". |
| 20 | + * For example, the word "goat" becomes "oatgma". |
| 21 | + * |
| 22 | + * Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1. |
| 23 | + * For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on. |
| 24 | + * |
| 25 | + * Return the final sentence representing the conversion from S to Goat Latin. |
| 26 | + * |
| 27 | + * Example 1: |
| 28 | + * |
| 29 | + * Input: "I speak Goat Latin" |
| 30 | + * Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" |
| 31 | + * |
| 32 | + * Example 2: |
| 33 | + * |
| 34 | + * Input: "The quick brown fox jumped over the lazy dog" |
| 35 | + * Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" |
| 36 | + * |
| 37 | + * Notes: |
| 38 | + * |
| 39 | + * S contains only uppercase, lowercase and spaces. Exactly one space between each word. |
| 40 | + * 1 <= S.length <= 100. |
| 41 | + */ |
| 42 | +public class _824 { |
| 43 | + |
| 44 | + public static class Solution1 { |
| 45 | + public String toGoatLatin(String S) { |
| 46 | + StringBuilder sb = new StringBuilder(); |
| 47 | + Set<Character> vowels = |
| 48 | + new HashSet(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); |
| 49 | + String[] words = S.split(" "); |
| 50 | + for (int i = 0; i < words.length; i++) { |
| 51 | + if (vowels.contains(words[i].charAt(0))) { |
| 52 | + String newWord = words[i] + "ma"; |
| 53 | + int j = i + 1; |
| 54 | + while (j-- > 0) { |
| 55 | + newWord += 'a'; |
| 56 | + } |
| 57 | + sb.append(newWord); |
| 58 | + sb.append(" "); |
| 59 | + } else { |
| 60 | + StringBuilder subSb = new StringBuilder(words[i].substring(1)); |
| 61 | + subSb.append(words[i].charAt(0)); |
| 62 | + subSb.append("ma"); |
| 63 | + int j = i + 1; |
| 64 | + while (j-- > 0) { |
| 65 | + subSb.append("a"); |
| 66 | + } |
| 67 | + sb.append(subSb.toString()); |
| 68 | + sb.append(" "); |
| 69 | + } |
| 70 | + } |
| 71 | + return sb.substring(0, sb.length() - 1); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments