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; + } +};