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
}
相关推荐
程序员-King.6 小时前
day158—回溯—全排列(LeetCode-46)
算法·leetcode·深度优先·回溯·递归
pumpkin8451410 小时前
01 Coze Studio项目中所有关键术语的详细解释和代码示例
golang
菜鸟233号13 小时前
力扣213 打家劫舍II java实现
java·数据结构·算法·leetcode
狐5713 小时前
2026-01-18-LeetCode刷题笔记-1895-最大的幻方
笔记·算法·leetcode
Q741_14713 小时前
C++ 队列 宽度优先搜索 BFS 力扣 662. 二叉树最大宽度 每日一题
c++·算法·leetcode·bfs·宽度优先
踩坑记录14 小时前
leetcode hot100 54.螺旋矩阵 medium
leetcode
王老师青少年编程14 小时前
2024年3月GESP真题及题解(C++七级): 俄罗斯方块
c++·题解·真题·gesp·csp·俄罗斯方块·七级
AC赳赳老秦15 小时前
Dify工作流+DeepSeek:运维自动化闭环(数据采集→报告生成)
android·大数据·运维·数据库·人工智能·golang·deepseek
源代码•宸16 小时前
Leetcode—3. 无重复字符的最长子串【中等】
经验分享·后端·算法·leetcode·面试·golang·string
历程里程碑16 小时前
哈希2:字母异位符分组
算法·leetcode·职场和发展