C语言求输出为出现次数最多的单词(有且仅有一个)及次数。

输入

输入若干行字符串(不超过10行)。每行字符数少于500个。

输出

输出一个单词和出现的次数,之间用一个空格隔开。

输入示例

there is more in the frying pan sweetgums i said turning misty eyes on her massive son we must build you up while we have got the chance i do not like the sound of that school food
nonsense petunia i never went hungry when i was at smeltings said uncle vernon heartily 00

输出示例

i 4

数据范围

输入为字符串,输出为字符串和int范围的整数

typedef struct {
    int cnt;
    char s[32];
}Word;

int cmp(void **a, void **b)
{
    return (strcmp(*((char**)a), *((char**)b)));
}
int cmp1(Word *a, Word *b)
{
    return (b->cnt - a->cnt);
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
char ** topKFrequent(char ** words, int wordsSize, int k, int* returnSize){
    int i;
    int idx = 0;
    Word *w = NULL;
    char **res = NULL;

    if (wordsSize == 0) {
        *returnSize = 0;
        return NULL;
    }

    if (wordsSize == 1) {
        *returnSize = 1;
        return words;
    }

    w = (Word*)malloc(wordsSize * sizeof(Word));
    res = (char**)malloc(k * sizeof(char*));

    for (i = 0; i < wordsSize; i++) {
        w[i].cnt = 0;
        w[i].s[0] = '\0';
    }

    qsort(words, wordsSize, sizeof(char*), cmp);

    w[0].cnt = 1;
    strcat(&w[0].s[0], words[0]);

    for (i = 1; i < wordsSize; i++) {
        if (strcmp(&w[idx].s[0], words[i]) == 0) {
            w[idx].cnt++;
            continue;
        }
        idx++;
        w[idx].cnt = 1;
        strcat(&w[idx].s[0], words[i]);
    }

    qsort(w, wordsSize, sizeof(Word), cmp1);

    for (i = 0; i < k; i++) {
       res[i] = (char*)malloc(32 * sizeof(char));
       
       if (res[i] != NULL) {
           res[i][0] = '\0';
           strcat(res[i], w[i].s);
       }
    }

    free(w);

    *returnSize = k;
    return res;
}

参考以上代码,将单词读入之后适配char ** words, int wordsSize,然后设置k=1,函数返回值即为所求
整体思路:统计-->降序排序-->取第一个单词

参考:(word字符统计,并升序排列)https://blog.csdn.net/qfl_sdu/article/details/117677520