Skip to content

Commit

Permalink
Create 2182. Construct String With Repeat Limit (#664)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Dec 17, 2024
2 parents dd12772 + 7b9446f commit 00e9d0f
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions 2182. Construct String With Repeat Limit
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution {
public:
string repeatLimitedString(string s, int repeatLimit) {
vector<int> v(26, 0);
for (int i = 0; i < s.size(); i++) v[s[i] - 'a']++;

priority_queue<pair<int, int>> 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;
}
};

0 comments on commit 00e9d0f

Please sign in to comment.