-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
77 lines (61 loc) · 990 Bytes
/
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
package main
import (
"container/heap"
"fmt"
"strings"
)
func main() {
fmt.Println(clearStars("aaba*"))
}
func clearStars(s string) string {
pq := &PQ{}
heap.Init(pq)
b := []byte(s)
for i := 0; i < len(s); i++ {
if s[i] == '*' {
b[i] = '-'
val := heap.Pop(pq).(check)
b[val.pos] = '-'
continue
}
heap.Push(pq, check{
s[i], i,
})
}
result := strings.Builder{}
for _, v := range b {
if v == '-' {
continue
}
result.WriteByte(v)
}
return result.String()
}
type PQ []check
type check struct {
b byte
pos 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 {
if pq[i].b == pq[j].b {
return pq[i].pos > pq[j].pos
}
return pq[i].b < pq[j].b
}
func (pq *PQ) Push(x interface{}) {
tmp := x.(check)
*pq = append(*pq, tmp)
}
func (pq *PQ) Pop() interface{} {
n := len(*pq)
tmp := (*pq)[n-1]
*pq = (*pq)[:n-1]
return tmp
}