go: add «2182. Construct String With Repeat Limit»
URL: https://leetcode.com/problems/construct-string-with-repeat-limit/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
e4878eb218
commit
97906d6431
1 changed files with 62 additions and 0 deletions
62
go/construct-string-with-repeat-limit.go
Normal file
62
go/construct-string-with-repeat-limit.go
Normal file
|
@ -0,0 +1,62 @@
|
||||||
|
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)
|
||||||
|
}
|
Loading…
Reference in a new issue