-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2182-Construct-String-With-Repeat-Limit.java
48 lines (40 loc) · 1.28 KB
/
2182-Construct-String-With-Repeat-Limit.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public String repeatLimitedString(String s, int repeatLimit) {
// freq.array to store character counts
int[] count = new int[26];
// count the freq. of each character
for (char ch:s.toCharArray()) {
count[ch-'a']++;
}
StringBuilder result = new StringBuilder();
int i=25;
while(i>=0) {
if (count[i] == 0) {
i--;
continue;
}
// convert index to character
char ch = (char) ('a' + i);
// append up to 'repeatLimit' times
int freq = Math.min(count[i],repeatLimit);
for (int k=0; k<freq; k++) {
result.append(ch);
}
count[i] -= freq;
if (count[i]>0) {
// find the next largest character
int j = i-1;
while (j >=0 && count[j]==0) {
j--;
}
if (j<0) {
break;
}
// append the next largest character once
result.append((char) ('a' + j));
count[j]--;
}
}
return result.toString();
}
}