From 97906d64316d3ed7e8bbe30888374188ba65bd92 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 29 Dec 2024 23:16:09 +0100 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB2182.=20Construct=20String=20?= =?UTF-8?q?With=20Repeat=20Limit=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/construct-string-with-repeat-limit/ Signed-off-by: Matej Focko --- go/construct-string-with-repeat-limit.go | 62 ++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 go/construct-string-with-repeat-limit.go diff --git a/go/construct-string-with-repeat-limit.go b/go/construct-string-with-repeat-limit.go new file mode 100644 index 0000000..6cc199e --- /dev/null +++ b/go/construct-string-with-repeat-limit.go @@ -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) +}