-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2182.cpp
More file actions
58 lines (52 loc) · 1.57 KB
/
2182.cpp
File metadata and controls
58 lines (52 loc) · 1.57 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
public:
string repeatLimitedString(string s, int repeatLimit) {
vector<int> charHash(26, 0);
for (char c : s) {
charHash[c - 'a']++;
}
int top = -1;
int second = -1;
queue<int> available;
for (int i = 25; i >= 0; i--) {
if (charHash[i] > 0) available.push(i);
}
top = available.front();
available.pop();
if (!available.empty()) {
second = available.front();
available.pop();
}
string out = "";
while (top >= 0) {
int maxRepeat = min(charHash[top], repeatLimit);
for (int i = 0; i < maxRepeat; i++) {
out += top + 'a';
charHash[top]--;
}
if (charHash[top] > 0 && second >= 0) {
out += second + 'a';
charHash[second]--;
if (charHash[second] == 0) {
second = -1;
if (!available.empty()) {
second = available.front();
available.pop();
}
}
}
else if (charHash[top] > 0 && second == -1) {
break;
}
else {
top = second;
second = -1;
if (!available.empty()) {
second = available.front();
available.pop();
}
}
}
return out;
}
};