【刷题打卡】824. 山羊拉丁文

94 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第22天,点击查看活动详情

1.描述

824. 山羊拉丁文 - 力扣(LeetCode) (leetcode-cn.com)

给你一个由若干单词组成的句子 sentence ,单词间由空格分隔。每个单词仅由大写和小写英文字母组成。

请你将句子转换为 “山羊拉丁文(Goat Latin)”(一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。山羊拉丁文的规则如下:

  • 如果单词以元音开头('a', 'e', 'i', 'o', 'u'),在单词后添加"ma"。
    • 例如,单词 "apple" 变为 "applema" 。
  • 如果单词以辅音字母开头(即,非元音字母),移除第一个字符并将它放到末尾,之后再添加"ma"。
    • 例如,单词 "goat" 变为 "oatgma" 。
  • 根据单词在句子中的索引,在单词最后添加与索引相同数量的字母'a',索引从 1 开始。
    • 例如,在第一个单词后添加 "a" ,在第二个单词后添加 "aa" ,以此类推。

返回将 sentence 转换为山羊拉丁文后的句子。

示例 1:

输入:sentence = "I speak Goat Latin"
输出:"Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

示例 2:

输入:sentence = "The quick brown fox jumped over the lazy dog"
输出:"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

提示:

  • 1 <= sentence.length <= 150
  • sentence 由英文字母和空格组成
  • sentence 不含前导或尾随空格
  • sentence 中的所有单词由单个空格分隔

2.分析

将处理每个单词的代码整合成一个函数,使用memxxx系列函数很容易进行处理。
返回的字符串再与已经处理过的字符串进行拼接,调用strcat函数。strcat函数使用经验比较少,在调用之前没有使用realloc多分配可以容纳处理的字符串,导致一直报heap oeverflow。
加上realloc后还是报overflow,原因是长度需要再加上1。
handle_latin()在处理后的单词后加了一个空格, 在处理最后一个单词时要去掉这个空格。

3.AC代码


bool is_vowel(char ch)
{
    switch (ch) {
        case 'a': case 'A':
        case 'e': case 'E':
        case 'i': case 'I':
        case 'o': case 'O':
        case 'u': case 'U':
            return true;
        default:
            return false;
    }
}

char* handle_latin(char *str, int start, int end, int word_idx)
{
    char *ma = "ma";
    int len = end - start + word_idx + 2; /* 2: ma */
    char *word = malloc(len + 2); /* 1 for space, and 1 for '\0'*/

    if (is_vowel(*(str+start))) {
        memcpy(word, str+start, end-start);
    } else {
        memcpy(word, str+start+1, end-start-1);
        word[end-start-1] = str[start];
    }
    memcpy(&word[end-start], ma, 2);
    memset(&word[len-word_idx], 'a', word_idx);
    word[len] = ' ';
    word[len+1] = '\0';
    return word;
}

char * toGoatLatin(char * S)
{
    int start = 0, end = 0, word_idx = 1;
    int lenS = strlen(S);
    char *res = malloc(1);
    res[0] = '\0';

    while (end <= lenS) {
        if (*(S+end) == ' ' || *(S+end) == '\0') {          
            char *word = handle_latin(S, start, end, word_idx);
            res = realloc(res, strlen(res) + strlen(word) + 1);
            strcat(res, word);
            start = end + 1;
            word_idx++;
        }
        end++;
    }
    res[strlen(res)-1] = '\0';
    return res;
}