Skip to content

Commit f5546f1

Browse files
authored
Merge pull request neetcode-gh#3305 from ResponseTime/main
0451-sort-characters-by-frequency.go
2 parents f1c0ff5 + 3c52f1a commit f5546f1

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
func frequencySort(s string) string {
2+
type charFreq struct {
3+
c rune
4+
f int
5+
}
6+
7+
mp := map[rune]int{}
8+
cs := []charFreq{}
9+
10+
for _, c := range s {
11+
mp[c]++
12+
}
13+
14+
for c, f := range mp {
15+
cs = append(cs, charFreq{c,f})
16+
}
17+
18+
sort.Slice(cs, func(i,j int) bool{
19+
return cs[i].f > cs[j].f
20+
})
21+
22+
ans := ""
23+
24+
for _, cf := range cs {
25+
ans += strings.Repeat(string(cf.c), cf.f)
26+
}
27+
28+
return ans
29+
}

0 commit comments

Comments
 (0)