From 7b9446fa01ee778441211068d0d2dab86d801bd9 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Tue, 17 Dec 2024 19:53:54 +0530 Subject: [PATCH] Create 2182. Construct String With Repeat Limit --- 2182. Construct String With Repeat Limit | 38 ++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 2182. Construct String With Repeat Limit diff --git a/2182. Construct String With Repeat Limit b/2182. Construct String With Repeat Limit new file mode 100644 index 0000000..bd54f46 --- /dev/null +++ b/2182. Construct String With Repeat Limit @@ -0,0 +1,38 @@ +class Solution { +public: + string repeatLimitedString(string s, int repeatLimit) { + vector v(26, 0); + for (int i = 0; i < s.size(); i++) v[s[i] - 'a']++; + + priority_queue> maxheap; + for (int i = 0; i < 26; i++) + if (v[i] > 0) maxheap.push({i, v[i]}); + + string result = ""; + + while (!maxheap.empty()) { + auto curr = maxheap.top(); + maxheap.pop(); + + char curr_char = 'a' + curr.first; + int count = min(curr.second, repeatLimit); + result.append(count, curr_char); + curr.second -= count; + + if (curr.second > 0) { + if (maxheap.empty()) break; + + auto next = maxheap.top(); + maxheap.pop(); + + char next_char = 'a' + next.first; + result.push_back(next_char); + next.second--; + + if (next.second > 0) maxheap.push(next); + maxheap.push(curr); + } + } + return result; + } +};