LeetCode Weekly Contest 82: Goat Latin

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.

大概参考了前10名中c++代码,选了2个分析了下代码逻辑。

Solution 1

通过单词首尾索引确定单词范围,然后依次处理每一个单词即可。

// by JOHNKRAM
class Solution {
public:
    string toGoatLatin(string S) {
        int n=S.size(),i,j,k,l;
        string ans="";
        for(i=0,k=1;i1,k++)
        {
            for(j=i;j' ';j++);  // 找到一个空格
            if(S[i]=='a'||S[i]=='e'||S[i]=='i'||S[i]=='o'||S[i]=='u'
            ||S[i]=='A'||S[i]=='E'||S[i]=='I'||S[i]=='O'||S[i]=='U')
                for(l=i;l// 若首字母为元音,则将此单词整个插入ans
            else  // 首字母非元音,则从第二个字母开始插入,最后插入首字母
            {
                for(l=i+1;l'm';  // 插入一个'm'
            for(l=0;l<=k;l++)ans+='a';  // 插入k+1个'a'
            if(j!=n)ans+=' ';  // 如果不是最后一个单词,则插入一个空格
        }
        return ans;
    }
};

Solution 2

因为字符串是以空格’ ‘分割的,可以将其转成istringstream类型,然后当成输入一次读入一个单词并处理。

// by szfck
class Solution {
public:
    bool ck(char ch) {
        string v = "aeiouAEIOU";
        return (v.find(ch) != string::npos);
    }
    string toGoatLatin(string S) {
        istringstream is(S);
        vector<string> res;
        string s;
        string A = "";
        while (is >> s) {
            A += "a";
            string t = "";
            if (ck(s[0])) {
                t = s + "ma";
            } else {
                t = s.substr(1) + s[0] + "ma";
            }
            t += A;
            res.push_back(t);
        }
        string ans = res[0];
        for (int i = 1; i < (int)res.size(); i++) {
            ans += " " + res[i];
        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode,leetcode,cpp)