aboutsummaryrefslogtreecommitdiffstats
path: root/451/main.go
blob: f025ce77e923b1f02d1cd5840eacf7c9e8fb9cdc (plain) (blame)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main

import (
	"fmt"
	"sort"
)

func frequencySort(s string) string {
	dict := func(s string) map[int]int {
		dict := make(map[int]int)

		for i := 0; i < len(s); i++ {
			if _, ok := dict[int(s[i])]; ok {
				dict[int(s[i])]++
			} else {
				dict[int(s[i])] = 1
			}
		}

		return dict
	}(s)

	type kv struct {
		key int
		val int
	}

	var ss []kv

	for k, v := range dict {
		ss = append(ss, kv{k, v})
	}

	sort.Slice(ss, func(i, j int) bool {
		return ss[i].val > ss[j].val
	})

	bytes := make([]byte, len(s), len(s))
	counter := 0
	for _, kv := range ss {
		for i := 0; i < kv.val; i++ {
			bytes[counter] = byte(kv.key)
			counter++
		}
	}

	return string(bytes)
}

func main() {
	fmt.Println(frequencySort("tree"))
	fmt.Println(frequencySort("cccaaa"))
	fmt.Println(frequencySort("Aabb"))
}