-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
30 lines (30 loc) · 890 Bytes
/
Solution.java
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
class Solution {
public String repeatLimitedString(String s, int repeatLimit) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) {
cnt[c - 'a']++;
}
StringBuilder ans = new StringBuilder();
for (int i = 25; i >= 0; --i) {
int j = i - 1;
while (true) {
for (int k = Math.min(repeatLimit, cnt[i]); k > 0; --k) {
cnt[i]--;
ans.append((char) ('a' + i));
}
if (cnt[i] == 0) {
break;
}
while (j >= 0 && cnt[j] == 0) {
--j;
}
if (j < 0) {
break;
}
cnt[j]--;
ans.append((char) ('a' + j));
}
}
return ans.toString();
}
}