824. 山羊拉丁文
給定一個由空格分割單詞的句子 S。每個單詞只包含大寫或小寫字母。
我們要將句子轉換爲 “Goat Latin”(一種類似於 豬拉丁文 - Pig Latin 的虛構語言)。
山羊拉丁文的規則如下:
如果單詞以元音開頭(a, e, i, o, u),在單詞後添加"ma"。
例如,單詞"apple"變爲"applema"。
如果單詞以輔音字母開頭(即非元音字母),移除第一個字符並將它放到末尾,之後再添加"ma"。
例如,單詞"goat"變爲"oatgma"。
根據單詞在句子中的索引,在單詞最後添加與索引相同數量的字母’a’,索引從1開始。
例如,在第一個單詞後添加"a",在第二個單詞後添加"aa",以此類推。
返回將 S 轉換爲山羊拉丁文後的句子。
示例 1:
輸入: “I speak Goat Latin”
輸出: “Imaa peaksmaaa oatGmaaaa atinLmaaaaa”
示例 2:
輸入: “The quick brown fox jumped over the lazy dog”
輸出: “heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa”
說明:
S 中僅包含大小寫字母和空格。單詞間有且僅有一個空格。
1 <= S.length <= 150。
class Solution {
public String toGoatLatin(String S) {
String[] words = S.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
sb.append(makeGoatLatin(words[i], i));
sb.append(' ');
}
String ans = sb.toString();
return ans.substring(0, ans.length() - 1);
}
private static String makeGoatLatin(String word, int index) {
StringBuilder sb = new StringBuilder();
char ch = word.charAt(0);
if (ch == 'a' || ch == 'e' || ch == 'i' ||ch == 'o' ||ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' ||ch == 'O' ||ch == 'U') {
sb.append(word);
} else {
sb.append(word.substring(1));
sb.append(ch);
}
sb.append("ma");
for (int i = 0; i <= index; i++) {
sb.append('a');
}
return sb.toString();
}
}