-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
108 lines (84 loc) · 1.35 KB
/
main.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"container/heap"
"fmt"
)
func main() {
fmt.Println(longestDiverseString(1, 2, 3))
}
func longestDiverseString(a int, b int, c int) string {
if a == 0 && b == 0 && c == 0 {
return ""
}
pq := &PQ{}
heap.Init(pq)
heap.Push(pq, Info{
B: 'a',
Count: a,
})
heap.Push(pq, Info{
B: 'b',
Count: b,
})
heap.Push(pq, Info{
B: 'c',
Count: c,
})
return runner("", pq)
}
func runner(s string, pq *PQ) string {
var arr []Info
for pq.Len() > 0 {
arr = append(arr, heap.Pop(pq).(Info))
}
if arr[0].Count == 0 {
return s
}
var check bool
// fmt.Println(arr, s)
if len(s) >= 2 {
if s[len(s)-1] == arr[0].B && s[len(s)-2] == arr[0].B {
if arr[1].Count == 0 {
return s
}
s += string(arr[1].B)
arr[1].Count--
check = true
}
}
if !check {
s += string(arr[0].B)
arr[0].Count--
}
for _, v := range arr {
heap.Push(pq, v)
}
return runner(s, pq)
}
type (
PQ []Info
Info struct {
B byte
Count int
}
)
func (pq PQ) Len() int {
return len(pq)
}
func (pq PQ) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
// max-heap
func (pq PQ) Less(i, j int) bool {
return pq[i].Count > pq[j].Count
}
func (pq *PQ) Push(x interface{}) {
tmp := x.(Info)
*pq = append(*pq, tmp)
}
func (pq *PQ) Pop() interface{} {
n := len(*pq)
tmp := (*pq)[n-1]
*pq = (*pq)[:n-1]
return tmp
}