-
Notifications
You must be signed in to change notification settings - Fork 17
/
reorganize-string.go
84 lines (62 loc) · 1.44 KB
/
reorganize-string.go
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"container/heap"
"strings"
)
type CharCount struct {
char rune
count int
}
type CharCountHeap []CharCount
func (heap CharCountHeap) Len() int {
return len(heap)
}
func (heap CharCountHeap) Less(i, j int) bool {
return heap[i].count > heap[j].count
}
func (heap CharCountHeap) Swap(i, j int) {
heap[i], heap[j] = heap[j], heap[i]
}
func (heap *CharCountHeap) Push(item interface{}) {
*heap = append(*heap, item.(CharCount))
}
func (heap *CharCountHeap) Pop() interface{} {
old := *heap
old_len := len(old)
result := old[old_len-1]
*heap = old[0 : old_len-1]
return result
}
func calculateCharCounts(s string) map[rune]int {
result := map[rune]int{}
for _, char := range s {
if val, ok := result[char]; ok {
result[char] = val + 1
} else {
result[char] = 1
}
}
return result
}
func reorganizeString(s string) string {
var sb strings.Builder
heapContainter := &CharCountHeap{}
heap.Init(heapContainter)
charCounts := calculateCharCounts(s)
for char, count := range charCounts {
heap.Push(heapContainter, CharCount{char, count})
}
prevCharCount := CharCount{'_', 0}
for len(*heapContainter) > 0 {
charCount := heap.Pop(heapContainter).(CharCount)
sb.WriteRune(charCount.char)
if prevCharCount.count > 0 {
heap.Push(heapContainter, prevCharCount)
}
prevCharCount = CharCount{charCount.char, charCount.count - 1}
}
if prevCharCount.count > 0 {
return ""
}
return sb.String()
}