Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
};
Loading