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;
}
相关推荐
圣保罗的大教堂1 小时前
leetcode 2348. 全 0 子数组的数目 中等
leetcode
曙曙学编程2 小时前
stm32——GPIO
c语言·c++·stm32·单片机·嵌入式硬件
Tisfy4 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率
tkevinjd7 小时前
图论\dp 两题
leetcode·动态规划·图论
XH华8 小时前
C语言第九章字符函数和字符串函数
c语言·开发语言
♞沉寂11 小时前
信号以及共享内存
linux·c语言·开发语言
1白天的黑夜111 小时前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表
上海迪士尼3511 小时前
力扣子集问题C++代码
c++·算法·leetcode
SunnyKriSmile11 小时前
【冒泡排序】
c语言·算法·排序算法