C语言 | Leetcode C语言题解之题451题根据字符出现频率排序

题目:

题解:

cpp 复制代码
#define HASH_FIND_CHAR(head, findint, out) HASH_FIND(hh, head, findint, sizeof(char), out)
#define HASH_ADD_CHAR(head, intfield, add) HASH_ADD(hh, head, intfield, sizeof(char), add)

struct HashTable {
    char key;
    int val;
    UT_hash_handle hh;
};

char* frequencySort(char* s) {
    struct HashTable* hashTable = NULL;
    int maxFreq = 0;
    int length = strlen(s);
    for (int i = 0; i < length; i++) {
        struct HashTable* tmp;
        HASH_FIND_CHAR(hashTable, &s[i], tmp);
        if (tmp == NULL) {
            tmp = malloc(sizeof(struct HashTable));
            tmp->key = s[i], tmp->val = 1;
            HASH_ADD_CHAR(hashTable, key, tmp);
            maxFreq = fmax(maxFreq, 1);
        } else {
            maxFreq = fmax(maxFreq, ++tmp->val);
        }
    }
    char* buckets[maxFreq + 1];
    int bucketsSize[maxFreq + 1];
    memset(bucketsSize, 0, sizeof(bucketsSize));
    int retSize = 0;
    struct HashTable *tmp, *iter;
    HASH_ITER(hh, hashTable, iter, tmp) {
        bucketsSize[iter->val]++;
        retSize += iter->val;
    }
    for (int i = 1; i <= maxFreq; i++) {
        buckets[i] = malloc(sizeof(char) * bucketsSize[i]);
    }
    memset(bucketsSize, 0, sizeof(bucketsSize));
    HASH_ITER(hh, hashTable, iter, tmp) {
        buckets[iter->val][bucketsSize[iter->val]++] = iter->key;
    }
    char* ret = malloc(sizeof(char) * (retSize + 1));
    retSize = 0;
    for (int i = maxFreq; i > 0; i--) {
        char* bucket = buckets[i];
        for (int j = 0; j < bucketsSize[i]; j++) {
            for (int k = 0; k < i; k++) {
                ret[retSize++] = bucket[j];
            }
        }
    }
    ret[retSize] = '\0';
    return ret;
}
相关推荐
Helene190013 分钟前
Leetcode 135-分发糖果
算法·leetcode
__AtYou__34 分钟前
Golang | Leetcode Golang题解之第452题用最少数量的箭引爆气球
leetcode·golang·题解
LluckyYH2 小时前
代码随想录Day 62|Floyd 算法精讲、A \* 算法精讲 (A star算法),题目:97. 小明逛公园、127. 骑士的攻击
数据结构·c++·算法·leetcode·图论
bcdaren2 小时前
《Windows PE》5.1 导出表
c语言·汇编·windows·pe
JUNAI_Strive_ving6 小时前
力扣题11~15
算法·leetcode
落叶、伤6 小时前
第15届蓝桥杯省赛B组c/c++ 0数字接龙
c语言·c++·蓝桥杯
921正在学习编程6 小时前
模拟实现strstr 找到母串中是否有与子串相同的部分(代码)
c语言·笔记·c#
Narnat6 小时前
判断链表是否有回环 C
c语言·数据结构·链表
大二转专业7 小时前
408算法题leetcode--第25天
考研·算法·leetcode