Skip to content

Commit 00e9d0f

Browse files
authored
Create 2182. Construct String With Repeat Limit (#664)
2 parents dd12772 + 7b9446f commit 00e9d0f

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public:
3+
string repeatLimitedString(string s, int repeatLimit) {
4+
vector<int> v(26, 0);
5+
for (int i = 0; i < s.size(); i++) v[s[i] - 'a']++;
6+
7+
priority_queue<pair<int, int>> maxheap;
8+
for (int i = 0; i < 26; i++)
9+
if (v[i] > 0) maxheap.push({i, v[i]});
10+
11+
string result = "";
12+
13+
while (!maxheap.empty()) {
14+
auto curr = maxheap.top();
15+
maxheap.pop();
16+
17+
char curr_char = 'a' + curr.first;
18+
int count = min(curr.second, repeatLimit);
19+
result.append(count, curr_char);
20+
curr.second -= count;
21+
22+
if (curr.second > 0) {
23+
if (maxheap.empty()) break;
24+
25+
auto next = maxheap.top();
26+
maxheap.pop();
27+
28+
char next_char = 'a' + next.first;
29+
result.push_back(next_char);
30+
next.second--;
31+
32+
if (next.second > 0) maxheap.push(next);
33+
maxheap.push(curr);
34+
}
35+
}
36+
return result;
37+
}
38+
};

0 commit comments

Comments
 (0)