Construct String With Repeat Limit LeetCode solution in Java

1
class Solution {
2
public String repeatLimitedString(String s, int repeatLimit) {
3
int[] counter = new int[26];
4
int max = 0;
5
for (char ch : s.toCharArray()) {
6
int curr = ch - 'a';
7
max = Math.max(max, curr);
8
counter[curr]++;
9
}
10
int repeated = 0;
11
StringBuilder builder = new StringBuilder();
12
while (max >= 0) {
13
builder.append((char) ('a' + max));
14
counter[max]--;
15
repeated++;
16
if (counter[max] == 0) {
17
max = findNextMax(counter, max - 1);
18
repeated = 0;
19
continue;
20
}
21
if (repeated == repeatLimit) {
22
// Greedy, use the next possible char once and get back to curr.
23
// if no other char available, the curr word is the largest subsequence.
24
int lower = findNextMax(counter, max - 1);
25
if (lower < 0) {
26
return builder.toString();
27
}
28
builder.append((char) ('a' + lower));
29
counter[lower]--;
30
repeated = 0;
31
}
32
}
33
return builder.toString();
34
}
35

36
private int findNextMax(int[] counter, int from) {
37
int curr = from;
38
while (curr >= 0) {
39
if (counter[curr] > 0) {
40
return curr;
41
}
42
curr--;
43
}
44
return curr;
45
}
46
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0