<easy>LeetCode Problem -- 824. 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:
    1. 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’.
    2. 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”.
    3. 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.

  • 分析:这道题是要求按照一定规则实现一个字符串替换算法,和Pig Latin类似,题目中要求有三点:
    1.如果遇到原音字母开头单词(a,e,i,o,u)则保留这个单词,并在这个单词末尾添加”ma”字符串
    2.如果遇到非原音字母开头的单词,将首字母移动到单词尾部,然后在尾部添加”ma”
    3.对于每个单词,在单词末尾添加额外的”a…”字符串,其中a的数目由单词出现的数目决定

  • 思路一:这道题其实主要问题在于每个单词分隔位置的判断,我在这里采用的是检测空格的位置,用一个bool变量来记录字符串的分隔情况,分隔处理完成之后就十分简单了。

class Solution {
public:
    string toGoatLatin(string S) {
        string res = "";
        string rear = "a";
        bool state_flag = true;
        string add_str = "";
        for (int i = 0; i < S.size(); i++) {
            res += S[i];
            if (state_flag) {
                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') {
                    add_str = "";
                } else {
                    add_str = S[i];
                    res.pop_back();
                }
                state_flag = false;
            }
            if (S[i] == ' ' || i == S.size() - 1)  {
                state_flag = true;
                add_str += "ma";
                add_str += rear;
                if (S[i] == ' ') res.insert(res.size() - 1, add_str);
                else res.insert(res.size(), add_str);
                rear += 'a';
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值