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
}
相关推荐
挥剑决浮云 -25 分钟前
leetcode 数组 27.移除元素
c++·算法·leetcode
7yewh1 小时前
C语言刷题 LeetCode 30天挑战 (七)哈希计数法
linux·c语言·c++·嵌入式硬件·算法·leetcode·哈希算法
技术卷2 小时前
GO网络编程(一):基础知识
开发语言·网络·golang
文sir.4 小时前
【leetcode】 45.跳跃游戏 ||
c语言·算法·leetcode
转调4 小时前
每日一练:零钱兑换
开发语言·c++·leetcode
hn小菜鸡5 小时前
LeetCode 面试经典150题 69.x的平方根
算法·leetcode·面试
GoppViper6 小时前
互联网前后端分离的开发场景,一般会员和数据权限的判断是放在前端还是后端?
前端·后端·架构·golang·前后端分离
xxxmmc6 小时前
Leetcode 218 The Skyline Problem
算法·leetcode
木向7 小时前
leetcode_238:除自身以外数组的乘积
数据结构·算法·leetcode