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
}
相关推荐
blxr_34 分钟前
力扣hot100前k个高频元素https://leetcode.cn/problems/top-k-frequent-elements/
算法·leetcode·职场和发展
朔北之忘 Clancy10 小时前
2025 CSP-J 第二轮真题解析
c++·青少年编程·题解·noip·csp·信奥赛·noi
longlongzihan10 小时前
LeetCode 17电话号码的字母组合:回溯算法(DFS)详解
c++·算法·leetcode·深度优先
茉莉玫瑰花茶11 小时前
GO [ 方法 ]
开发语言·后端·golang
王老师青少年编程15 小时前
2026年9月GESP真题及题解(C++七级):括号序列
题解·真题·gesp·csp·c++七级·括号序列·2026年9月
smj2302_7968265216 小时前
解决leetcode第4064题至多一次取反能被k整除的最长子数组II
python·算法·leetcode
青山木16 小时前
Hot 100 --- 下一个排列
java·数据结构·算法·leetcode
垆边人似月.16 小时前
字符串重排后最大字典序
算法·leetcode·职场和发展
代码什么用17 小时前
LeetCode-42. 接雨水
算法·leetcode
茉莉玫瑰花茶18 小时前
GO [ 函数 ]
开发语言·后端·golang