weixin_39965936 2021-07-08 23:56 采纳率: 68.8%
浏览 278
已结题

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范围的整数

  • 写回答

2条回答 默认 最新

  • 雷鬼007 2021-07-09 00:18
    关注
    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,函数返回值即为所求
    整体思路:统计-->降序排序-->取第一个单词

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月9日
  • 已采纳回答 10月1日
  • 创建了问题 7月8日

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵