[LeetCode] 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. 

 

Example 1:

Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

Example 2:

Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

 

Notes:

  • S contains only uppercase, lowercase and spaces. Exactly one space between each word.
  • 1 <= S.length <= 150.

 

這道題讓我們將一句話轉為山羊拉丁文,有幾個規則,如果單詞是元音開頭的,那么直接在但此后加ma,(為啥不是咩mie,西方的羊就是叫ma么,不知為何想起了老友記中Janice的笑聲-.-|||,但其實Janice在劇中的聲音是有意為之的,看過演員本人的訪談節目,相當正常,不得不說演員啊,聲優啊,都是怪物,扯遠了~),如果是非元音開頭的單詞,那么把首字母移到末尾,並且加ma。還有就是根據當前是第幾個單詞,后面加幾個a,估計是為了模仿羊叫聲,拉長音,感覺更像綿羊音一樣。此題難度不是很大,就照題目要求來做,不需要啥特別的技巧。首先為了快速檢測開頭字母是否為元音,我們將所有元音加入一個HashSet,注意大小寫的元音都要加進去。然后要一個單詞一個單詞的處理,這里我們使用C++的字符串流類來快速的提取單詞,對於每個提取出的單詞,我們先加上一個空格,然后判斷開頭字母是否為元音,是的話直接加上,不然就去子串去掉首字母,然后將首字母加到末尾。后面再加上ma,還有相對應數目個a。這里我們定義一個變量cnt,初始化為1,每處理一個單詞,cnt自增1,這樣我們就知道需要加的a的個數了,最后別忘了把結果res的首空格去掉,參見代碼如下:

 

class Solution {
public:
    string toGoatLatin(string S) {
        unordered_set<char> vowel{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
        istringstream ss(S);
        string res, t;
        int cnt = 1;
        while (ss >> t) {
            res += ' ' + (vowel.count(t[0]) ? t : t.substr(1) + t[0]) + "ma" + string(cnt, 'a');
            ++cnt;
        }
        return res.substr(1);
    }
};

 

參考資料:

https://leetcode.com/problems/goat-latin/

https://leetcode.com/problems/goat-latin/discuss/126973/Short-C%2B%2B-solution-using-io-stringstream

https://leetcode.com/problems/goat-latin/discuss/127024/C%2B%2BJavaPython-Straight-Forward-Solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM