LeetCode 451. 根据字符出现频率排序
题目描述
思路分析
自定义排序
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func frequencySort(s string) string {
freq := make(map[byte]int)
chars := []byte(s)
for _, c := range chars {
freq[c]++
}
sort.Slice(chars, func(i, j int) bool {
if freq[chars[i]] == freq[chars[j]] {
return chars[i] < chars[j] // 按字母顺序排序
}
return freq[chars[i]] > freq[chars[j]] // 按频率排序
})
return string(chars)
}
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
func frequencySort(s string) string {
// 统计字符频率
freqMap := make(map[rune]int)
for _, ch := range s {
freqMap[ch]++
}
// 转成切片用于排序
type pair struct {
ch rune
freq int
}
var pairs []pair
for ch, freq := range freqMap {
pairs = append(pairs, pair{ch, freq})
}
// 降序排序
sort.Slice(pairs, func(i, j int) bool {
return pairs[i].freq > pairs[j].freq
})
var builder strings.Builder
for _, p := range pairs {
for i := 0; i < p.freq; i++ {
builder.WriteRune(p.ch)
}
}
return builder.String()
}
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用