forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.go
49 lines (45 loc) · 924 Bytes
/
Solution2.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
func reorganizeString(s string) string {
return rearrangeString(s, 2)
}
func rearrangeString(s string, k int) string {
cnt := map[byte]int{}
for i := range s {
cnt[s[i]]++
}
pq := hp{}
for c, v := range cnt {
heap.Push(&pq, pair{v, c})
}
ans := []byte{}
q := []pair{}
for len(pq) > 0 {
p := heap.Pop(&pq).(pair)
v, c := p.v, p.c
ans = append(ans, c)
q = append(q, pair{v - 1, c})
if len(q) >= k {
p = q[0]
q = q[1:]
if p.v > 0 {
heap.Push(&pq, p)
}
}
}
if len(ans) == len(s) {
return string(ans)
}
return ""
}
type pair struct {
v int
c byte
}
type hp []pair
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool {
a, b := h[i], h[j]
return a.v > b.v
}
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }