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
}
相关推荐
君君思密达10 分钟前
LeetCode Hot 100 题目详解-滑动窗口
算法·leetcode·职场和发展
fqq39 小时前
力扣刷题前置Java语法
算法·leetcode·职场和发展
半夏微凉半夏殇12 小时前
x11与weston对比,优先选哪个
leetcode·均值算法·eclipse
爱编程的小新☆17 小时前
【LeetCode】从递归到 Flood Fill:5 道题吃透 DFS 的选择、回溯与标记
java·算法·leetcode·深度优先·回溯·flood fill
evans在进步17 小时前
LeetCode 33:搜索旋转排序数组——Java 两阶段二分查找详解
java·python·leetcode
alphaTao17 小时前
LeetCode 每日一题 2026/8/10-2026/8/16
算法·leetcode
Forever Nore18 小时前
LeetCode 13 罗马数字转整数 - 按规则处理
linux·服务器·leetcode
旖旎夜光19 小时前
LeetCode 904:水果成篮(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
ZC跨境爬虫20 小时前
LeetCode 27. 移除元素(双指针详解 + Java Python 多解法对比)
java·python·leetcode
圣殿骑士-Khtangc21 小时前
Go错误处理最佳实践进阶从error到panic的完整指南
golang