Goat Latin

題目
A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.

We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)

The rules of Goat Latin are as follows:

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 to the end and so on.
Return the final sentence representing the conversion from S to Goat Latin.

答案

class Solution {
    public String toGoatLatin(String S) {
        String[] words = S.split(" ");
        for(int i = 0; i < words.length; i++) {
            // Apply rule 1 and 2
            String wordLower = words[i].toLowerCase();
            char first = wordLower.charAt(0);
            if("aeiou".indexOf(first) < 0) {
                // not a vowel
                words[i] = words[i].substring(1) + words[i].charAt(0) + "ma";
            }
            else {
                // is a vowel
                words[i] = words[i] + "ma";
            }
            
            // Apply rule 3
            int index = i + 1;
            String as = "";
            for(int j = 0; j < index; j++) as = as + "a";
            words[i] = words[i] + as;
        }
        
        return String.join(" ", words);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評論 0 10
  • raft 學(xué)習(xí)筆記 最近在學(xué)習(xí) 6.824 的分布式課程.學(xué)習(xí)到 Raft 算法. 寫篇文章作為記錄. 什么是 R...
    hunterer閱讀 1,784評論 0 0
  • 這篇文章簡單介紹下“數(shù)獨(dú)求解器”怎么用程序?qū)崿F(xiàn)??文章背景圖片是一個比較難的數(shù)獨(dú)問題,感興趣的可以試著手動求解啊。...
    faithefeng閱讀 446評論 0 1
  • 本控件項(xiàng)目地址,希望能給個start,歡迎大家交流指正。 簡單說明 有簡單動畫效果,高度可根據(jù)內(nèi)容自適應(yīng),點(diǎn)擊事件...
    Simba_LX閱讀 1,892評論 4 11

友情鏈接更多精彩內(nèi)容