File tree Expand file tree Collapse file tree 3 files changed +77
-0
lines changed
solution/0400-0499/0451.Sort Characters By Frequency Expand file tree Collapse file tree 3 files changed +77
-0
lines changed Original file line number Diff line number Diff line change @@ -117,6 +117,34 @@ class Solution {
117
117
}
118
118
```
119
119
120
+ ### ** Go**
121
+
122
+ 用结构体排序进行模拟
123
+
124
+ ``` go
125
+ type pair struct {
126
+ b byte
127
+ cnt int
128
+ }
129
+
130
+ func frequencySort (s string ) string {
131
+ freq := make (map [byte ]int )
132
+ for _ , r := range s {
133
+ freq[byte (r)]++
134
+ }
135
+ a := make ([]pair, 0 )
136
+ for k , v := range freq {
137
+ a = append (a, pair{b: k, cnt: v})
138
+ }
139
+ sort.Slice (a, func (i, j int ) bool { return a[i].cnt > a[j].cnt })
140
+ var sb strings.Builder
141
+ for _ , p := range a {
142
+ sb.Write (bytes.Repeat ([]byte {p.b }, p.cnt ))
143
+ }
144
+ return sb.String ()
145
+ }
146
+ ```
147
+
120
148
### ** ...**
121
149
122
150
```
Original file line number Diff line number Diff line change @@ -101,6 +101,34 @@ class Solution {
101
101
}
102
102
```
103
103
104
+ ### ** Go**
105
+
106
+ Simulation with structure sorting.
107
+
108
+ ``` go
109
+ type pair struct {
110
+ b byte
111
+ cnt int
112
+ }
113
+
114
+ func frequencySort (s string ) string {
115
+ freq := make (map [byte ]int )
116
+ for _ , r := range s {
117
+ freq[byte (r)]++
118
+ }
119
+ a := make ([]pair, 0 )
120
+ for k , v := range freq {
121
+ a = append (a, pair{b: k, cnt: v})
122
+ }
123
+ sort.Slice (a, func (i, j int ) bool { return a[i].cnt > a[j].cnt })
124
+ var sb strings.Builder
125
+ for _ , p := range a {
126
+ sb.Write (bytes.Repeat ([]byte {p.b }, p.cnt ))
127
+ }
128
+ return sb.String ()
129
+ }
130
+ ```
131
+
104
132
### ** ...**
105
133
106
134
```
Original file line number Diff line number Diff line change
1
+ type pair struct {
2
+ b byte
3
+ cnt int
4
+ }
5
+
6
+ func frequencySort (s string ) string {
7
+ freq := make (map [byte ]int )
8
+ for _ , r := range s {
9
+ freq [byte (r )]++
10
+ }
11
+ a := make ([]pair , 0 )
12
+ for k , v := range freq {
13
+ a = append (a , pair {b : k , cnt : v })
14
+ }
15
+ sort .Slice (a , func (i , j int ) bool { return a [i ].cnt > a [j ].cnt })
16
+ var sb strings.Builder
17
+ for _ , p := range a {
18
+ sb .Write (bytes .Repeat ([]byte {p .b }, p .cnt ))
19
+ }
20
+ return sb .String ()
21
+ }
You can’t perform that action at this time.
0 commit comments