-
Notifications
You must be signed in to change notification settings - Fork 12
/
solution.go
70 lines (59 loc) · 1.55 KB
/
solution.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
import (
"container/heap"
"strings"
)
type CharCount struct {
count int
ch byte
}
// Priority queue implementation for Go
type MaxHeap []CharCount
func (h MaxHeap) Len() int { return len(h) }
func (h MaxHeap) Less(i, j int) bool { return h[i].count > h[j].count }
func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x interface{}) {
*h = append(*h, x.(CharCount))
}
func (h *MaxHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func longestDiverseString(a int, b int, c int) string {
pq := &MaxHeap{}
heap.Init(pq)
if a > 0 {
heap.Push(pq, CharCount{a, 'a'})
}
if b > 0 {
heap.Push(pq, CharCount{b, 'b'})
}
if c > 0 {
heap.Push(pq, CharCount{c, 'c'})
}
var result strings.Builder
for pq.Len() > 0 {
first := heap.Pop(pq).(CharCount)
if result.Len() >= 2 && result.String()[result.Len()-1] == first.ch && result.String()[result.Len()-2] == first.ch {
if pq.Len() == 0 {
break
}
second := heap.Pop(pq).(CharCount)
result.WriteByte(second.ch)
second.count--
if second.count > 0 {
heap.Push(pq, second)
}
heap.Push(pq, first)
} else {
result.WriteByte(first.ch)
first.count--
if first.count > 0 {
heap.Push(pq, first)
}
}
}
return result.String()
}