-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2182-string-repeat-limit.dart
54 lines (42 loc) · 1.25 KB
/
2182-string-repeat-limit.dart
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
class Solution {
String repeatLimitedString(String s, int repeatLimit) {
Map<String, int> frequency = {};
for (int i = 0; i < s.length; i++) {
String c = s[i];
frequency[c] = (frequency[c] ?? 0) + 1;
}
List<String> chars = frequency.keys.toList()
..sort((a, b) => b.compareTo(a));
StringBuffer result = StringBuffer();
int i = 0;
while (i < chars.length) {
String currentChar = chars[i];
int currentFreq = frequency[currentChar]!;
int count = 0;
while (count < repeatLimit && currentFreq > 0) {
result.write(currentChar);
currentFreq--;
count++;
}
frequency[currentChar] = currentFreq;
if (currentFreq > 0) {
int j = i + 1;
while (j < chars.length && frequency[chars[j]] == 0) {
j++;
}
if (j >= chars.length) break;
String nextChar = chars[j];
result.write(nextChar);
frequency[nextChar] = frequency[nextChar]! - 1;
} else {
i++;
}
}
return result.toString();
}
}
void main() {
Solution solution = Solution();
print(solution.repeatLimitedString("cczazcc", 3)); // Output: "zzcccac"
print(solution.repeatLimitedString("aababab", 2)); // Output: "bbabaa"
}