Matej Focko
97906d6431
URL: https://leetcode.com/problems/construct-string-with-repeat-limit/ Signed-off-by: Matej Focko <me@mfocko.xyz>
62 lines
937 B
Go
62 lines
937 B
Go
package main
|
|
|
|
import (
|
|
"cmp"
|
|
|
|
pq "github.com/emirpasic/gods/v2/queues/priorityqueue"
|
|
)
|
|
|
|
func repeatLimitedString(s string, repeatLimit int) string {
|
|
charReversed := func(a, b rune) int {
|
|
return cmp.Compare(b, a)
|
|
}
|
|
|
|
getFreqs := func() map[rune]int {
|
|
f := make(map[rune]int)
|
|
for _, c := range s {
|
|
count, found := f[c]
|
|
|
|
if found {
|
|
count++
|
|
} else {
|
|
count = 1
|
|
}
|
|
|
|
f[c] = count
|
|
}
|
|
|
|
return f
|
|
}
|
|
freqs := getFreqs()
|
|
|
|
q := pq.NewWith(charReversed)
|
|
for k, _ := range freqs {
|
|
q.Enqueue(k)
|
|
}
|
|
|
|
result := []rune{}
|
|
for c, ok := q.Dequeue(); ok; c, ok = q.Dequeue() {
|
|
k := min(freqs[c], repeatLimit)
|
|
for i := 0; i < k; i++ {
|
|
result = append(result, c)
|
|
}
|
|
freqs[c] -= k
|
|
|
|
if freqs[c] > 0 {
|
|
nextC, ok := q.Dequeue()
|
|
if !ok {
|
|
break
|
|
}
|
|
|
|
result = append(result, nextC)
|
|
freqs[nextC]--
|
|
|
|
if freqs[nextC] > 0 {
|
|
q.Enqueue(nextC)
|
|
}
|
|
q.Enqueue(c)
|
|
}
|
|
}
|
|
|
|
return string(result)
|
|
}
|