File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments