|
| 1 | +package com.wdbyte.leetcode; |
| 2 | + |
| 3 | +/** |
| 4 | + * https://leetcode-cn.com/problems/goat-latin/ |
| 5 | + * 824. 山羊拉丁文 |
| 6 | + * |
| 7 | + * @author niulang |
| 8 | + * @date 2022/04/21 |
| 9 | + */ |
| 10 | +public class LeetCode824 { |
| 11 | + |
| 12 | + public static void main(String[] args) { |
| 13 | + //String goatLatin = new LeetCode824().toGoatLatin("I speak Goat Latin"); |
| 14 | + String goatLatin = new LeetCode824().toGoatLatin("The quick brown fox jumped over the lazy dog"); |
| 15 | + //String goatLatin = new LeetCode824().toGoatLatin("goat"); |
| 16 | + System.out.println(goatLatin); |
| 17 | + } |
| 18 | + |
| 19 | + /** |
| 20 | + * 如果单词以元音开头('a', 'e', 'i', 'o', 'u'),在单词后添加"ma"。 |
| 21 | + * 例如,单词 "apple" 变为 "applema" 。 |
| 22 | + * 如果单词以辅音字母开头(即,非元音字母),移除第一个字符并将它放到末尾,之后再添加"ma"。 |
| 23 | + * 例如,单词 "goat" 变为 "oatgma" 。 |
| 24 | + * 根据单词在句子中的索引,在单词最后添加与索引相同数量的字母'a',索引从 1 开始。 |
| 25 | + * 例如,在第一个单词后添加 "a" ,在第二个单词后添加 "aa" ,以此类推。 |
| 26 | + * |
| 27 | + * @param sentence |
| 28 | + * @return |
| 29 | + */ |
| 30 | + public String toGoatLatin(String sentence) { |
| 31 | + String[] array = sentence.split(" "); |
| 32 | + StringBuilder builder = new StringBuilder(); |
| 33 | + for (int i = 0; i < array.length; i++) { |
| 34 | + String word = array[i]; |
| 35 | + if (builder.length() != 0) { |
| 36 | + builder.append(" "); |
| 37 | + } |
| 38 | + // 元音开头 |
| 39 | + char[] chars = word.toCharArray(); |
| 40 | + if (chars[0] == 'A' || chars[0] == 'E' || chars[0] == 'I' || chars[0] == 'O' || chars[0] == 'U' || |
| 41 | + chars[0] == 'a' || chars[0] == 'e' || chars[0] == 'i' || chars[0] == 'o' || chars[0] == 'u') { |
| 42 | + builder.append(word).append("ma"); |
| 43 | + } else { |
| 44 | + // 辅音开头 |
| 45 | + for (int j = 0; j < chars.length; j++) { |
| 46 | + if (j == 0) {continue;} |
| 47 | + builder.append(chars[j]); |
| 48 | + } |
| 49 | + builder.append(chars[0]).append("ma"); |
| 50 | + } |
| 51 | + for (int j = 0; j <= i; j++) { |
| 52 | + builder.append("a"); |
| 53 | + } |
| 54 | + } |
| 55 | + return builder.toString(); |
| 56 | + } |
| 57 | +} |
0 commit comments