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
// @Title: 根据字符出现频率排序 (Sort Characters By Frequency)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 12 ms
// @Memory: 5 MB
func frequencySort(s string) string {
	bytes := []byte(s)
	record := make(map[byte]int)
	for _, v := range bytes {
		record[v]++
	}

	ret := make([][]byte, len(bytes)+1) // 注意桶的容量为len(nums)+1
	for k, v := range record {
		ret[v] = append(ret[v], k)
	}

	res := make([]byte, 0)
	for i:=len(ret)-1;i>0;i-- {
	// for i := range ret {
		for _,k := range ret[i] {

		for j := i;j>0;j-- {
		res = append(res, k)
		}
		}
	}
	return string(res)
}