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
| class Solution { public String repeatLimitedString(String s, int repeatLimit) { int n = s.length(); int[] wordCount = new int[26]; for (int i = 0; i < n; i++) { wordCount[s.charAt(i) - 'a']++; } PriorityQueue<int[]> priorityQueue = new PriorityQueue<>((arr1, arr2) -> arr2[1] - arr1[1]); for (int i = 0; i < 26; i++) { if (wordCount[i] > 0) { priorityQueue.offer(new int[] { wordCount[i], i }); } } StringBuffer sb = new StringBuffer(); while (!priorityQueue.isEmpty()) { int[] arr = priorityQueue.poll(); int count = Math.min(arr[0], repeatLimit); char ch = (char) (arr[1] + 'a'); for (int i = 0; i < count; i++) { sb.append(ch); } if (arr[0] > repeatLimit) { if (priorityQueue.isEmpty()) { break; } int[] arr2 = priorityQueue.poll(); sb.append((char) (arr2[1] + 'a')); if (arr2[0] > 1) { arr2[0]--; priorityQueue.offer(arr2); } arr[0] -= repeatLimit; priorityQueue.offer(arr); } } return sb.toString(); } }
|