题解 | 小红书推荐系统

小红书推荐系统

https://www.nowcoder.com/practice/e5b39c9034a84bf2a5e026b2b9b973d0

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
    char* word;
    int count;
} WordCount;

int cmp(const void* a, const void* b) {
    const WordCount* wa = (const WordCount*)a;
    const WordCount* wb = (const WordCount*)b;

    if (wa->count != wb->count) {
        return wb->count - wa->count;
    }
    return strcmp(wa->word, wb->word);
}

int cmp_strings(const void* a, const void* b) {
    return strcmp(*(const char**)a, *(const char**)b);
}

int main(void) {
    char ch[100005];
    fgets(ch, sizeof(ch), stdin);
    ch[strcspn(ch, "\n")] = 0;

    char* a[100005];
    int i = 0;

    char* trtok = strtok(ch, " ");
    while (trtok != NULL && i < 100005) {
        a[i++] = trtok;
        trtok = strtok(NULL, " ");
    }
    qsort(a, i, sizeof(char*), cmp_strings);

    WordCount* words = (WordCount*)malloc(i * sizeof(WordCount));
    int unique_count = 0, current_count = 1;
    for (int j = 1; j <= i; j++) {
        if (j < i && strcmp(a[j], a[j - 1]) == 0)
            current_count++;
        else {
            if (current_count >= 3) {
                words[unique_count].word = a[j - 1];
                words[unique_count].count = current_count;
                unique_count++;
            }
            current_count = 1;
        }
    }
    qsort(words, unique_count, sizeof(WordCount), cmp);

    for (int k = 0; k < unique_count; k++)
        printf("%s\n", words[k].word);

    free(words);
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务