forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstruct-string-with-repeat-limit.cpp
More file actions
40 lines (39 loc) · 1 KB
/
construct-string-with-repeat-limit.cpp
File metadata and controls
40 lines (39 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Time: O(26 * n)
// Space: O(26)
// greedy
class Solution {
public:
string repeatLimitedString(string s, int repeatLimit) {
vector<int> cnt(26);
for (const auto& c : s) {
++cnt[c - 'a'];
}
string result;
int top1 = 25;
for (;;) {
for (; top1 >= 0; --top1) {
if (cnt[top1]) {
break;
}
}
if (top1 == -1) {
break;
}
const int c = min(cnt[top1], repeatLimit - static_cast<int>(!empty(result) && result.back() == 'a' + top1));
cnt[top1] -= c;
result.append(c, 'a' + top1);
int top2 = top1 - 1;
for (; top2 >= 0; --top2) {
if (cnt[top2]) {
break;
}
}
if (top2 == -1) {
break;
}
--cnt[top2];
result.push_back('a' + top2);
}
return result;
}
};