-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComplete BT102 training.cpp
43 lines (37 loc) · 1.08 KB
/
Complete BT102 training.cpp
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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
string repeatLimitedString(string s, int repeatLimit) {
sort(s.rbegin(), s.rend());
string result;
int freq = 1;
int pointer = 0;
for (int i = 0; i < s.size(); ++i) {
if (!result.empty() && result.back() == s[i]) {
if (freq < repeatLimit) {
result += s[i];
freq++;
} else {
pointer = max(pointer, i + 1);
while (pointer < s.size() && s[pointer] == s[i]) {
pointer++;
}
if (pointer < s.size()) {
result += s[pointer];
swap(s[i], s[pointer]);
freq = 1;
} else {
break;
}
}
} else {
result += s[i];
freq = 1;
}
}
return result;
}
};