Golang | Leetcode Golang题解之第451题根据字符出现频率排序

题目:

题解:

Go 复制代码
func frequencySort(s string) string {
    cnt := map[byte]int{}
    maxFreq := 0
    for i := range s {
        cnt[s[i]]++
        maxFreq = max(maxFreq, cnt[s[i]])
    }

    buckets := make([][]byte, maxFreq+1)
    for ch, c := range cnt {
        buckets[c] = append(buckets[c], ch)
    }

    ans := make([]byte, 0, len(s))
    for i := maxFreq; i > 0; i-- {
        for _, ch := range buckets[i] {
            ans = append(ans, bytes.Repeat([]byte{ch}, i)...)
        }
    }
    return string(ans)
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
相关推荐
Paul_09207 分钟前
golang面经——内存相关模块
服务器·网络·golang
gopyer4 小时前
180课时吃透Go语言游戏后端开发6:Go语言的循环语句
开发语言·游戏·golang·循环语句
天选之女wow7 小时前
【代码随想录算法训练营——Day28】贪心算法——134.加油站、135.分发糖果、860.柠檬水找零、406.根据身高重建队列
算法·leetcode·贪心算法
flashlight_hi9 小时前
LeetCode 分类刷题:1901. 寻找峰值 II
python·算法·leetcode
未知陨落13 小时前
LeetCode:95.编辑距离
算法·leetcode
名誉寒冰16 小时前
【LeetCode】454. 四数相加 II 【分组+哈希表】详解
算法·leetcode·散列表
tao35566717 小时前
【Python刷力扣hot100】49. Group Anagrams
开发语言·python·leetcode
夏鹏今天学习了吗17 小时前
【LeetCode热题100(35/100)】LRU 缓存
算法·leetcode·缓存
Q741_14720 小时前
C++ 位运算 高频面试考点 力扣137. 只出现一次的数字 II 题解 每日一题
c++·算法·leetcode·面试·位运算