-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCharacterOperations.java
55 lines (43 loc) · 1.45 KB
/
CharacterOperations.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
49
50
51
52
53
54
55
import java.util.*;
class Solution {
public static String repeatLimitedString(String s, int repeatLimit) {
int[] freq = new int[26];
for (char c : s.toCharArray()) {
freq[c - 'a']++;
}
PriorityQueue<Character> maxHeap = new PriorityQueue<>((a, b) -> b - a);
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
maxHeap.add((char) (i + 'a'));
}
}
StringBuilder result = new StringBuilder();
while (!maxHeap.isEmpty()) {
char current = maxHeap.poll();
int count = Math.min(freq[current - 'a'], repeatLimit);
for (int i = 0; i < count; i++) {
result.append(current);
}
freq[current - 'a'] -= count;
if (freq[current - 'a'] > 0) {
if (!maxHeap.isEmpty()) {
char next = maxHeap.poll();
result.append(next);
freq[next - 'a']--;
if (freq[next - 'a'] > 0) {
maxHeap.add(next);
}
} else {
break;
}
maxHeap.add(current);
}
}
return result.toString();
}
public static void main(String[] args) {
String str = "aabbbcc";
int repeatLimit = 2;
System.out.println(repeatLimitedString(str, repeatLimit));
}
}