1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| type CharCount struct {
Char byte
Count int
}
func frequencySort(s string) string {
// 统计字符频率
countMap := make(map[byte]int)
for i := 0; i < len(s); i++ {
countMap[s[i]]++
}
// 将字符频率存入结构体切片
counts := make([]CharCount, 0, len(countMap))
for char, count := range countMap {
counts = append(counts, CharCount{char, count})
}
// 按频率降序排序
sort.Slice(counts, func(i, j int) bool {
return counts[i].Count > counts[j].Count
})
// 构建结果字符串
res := make([]byte, 0, len(s))
for _, charCount := range counts {
for i := 0; i < charCount.Count; i++ {
res = append(res, charCount.Char)
}
}
return string(res)
}
|