|
30 | 30 | */ |
31 | 31 | public class _358 { |
32 | 32 |
|
33 | | - public String rearrangeString(String s, int k) { |
34 | | - Map<Character, Integer> count = new HashMap<>(); |
35 | | - for (char c : s.toCharArray()) { |
36 | | - count.put(c, count.getOrDefault(c, 0) + 1); |
37 | | - } |
| 33 | + public static class Solution1 { |
| 34 | + public String rearrangeString(String s, int k) { |
| 35 | + Map<Character, Integer> count = new HashMap<>(); |
| 36 | + for (char c : s.toCharArray()) { |
| 37 | + count.put(c, count.getOrDefault(c, 0) + 1); |
| 38 | + } |
38 | 39 |
|
39 | | - PriorityQueue<Map.Entry<Character, Integer>> heap = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue()); |
40 | | - heap.addAll(count.entrySet()); |
| 40 | + PriorityQueue<Map.Entry<Character, Integer>> heap = |
| 41 | + new PriorityQueue<>((a, b) -> b.getValue() - a.getValue()); |
| 42 | + heap.addAll(count.entrySet()); |
41 | 43 |
|
42 | | - Queue<Map.Entry<Character, Integer>> waitQueue = new LinkedList<>(); |
| 44 | + Queue<Map.Entry<Character, Integer>> waitQueue = new LinkedList<>(); |
43 | 45 |
|
44 | | - StringBuilder stringBuilder = new StringBuilder(); |
45 | | - while (!heap.isEmpty()) { |
46 | | - Map.Entry<Character, Integer> entry = heap.poll(); |
47 | | - stringBuilder.append(entry.getKey()); |
48 | | - entry.setValue(entry.getValue() - 1); |
49 | | - waitQueue.offer(entry); |
50 | | - if (waitQueue.size() < k) { |
51 | | - continue; //there's only k-1 chars in the waitHeap, not full yet |
52 | | - } |
53 | | - Map.Entry<Character, Integer> front = waitQueue.poll(); |
54 | | - if (front.getValue() > 0) { |
55 | | - heap.offer(front); |
| 46 | + StringBuilder stringBuilder = new StringBuilder(); |
| 47 | + while (!heap.isEmpty()) { |
| 48 | + Map.Entry<Character, Integer> entry = heap.poll(); |
| 49 | + stringBuilder.append(entry.getKey()); |
| 50 | + entry.setValue(entry.getValue() - 1); |
| 51 | + waitQueue.offer(entry); |
| 52 | + if (waitQueue.size() < k) { |
| 53 | + continue; //there's only k-1 chars in the waitHeap, not full yet |
| 54 | + } |
| 55 | + Map.Entry<Character, Integer> front = waitQueue.poll(); |
| 56 | + if (front.getValue() > 0) { |
| 57 | + heap.offer(front); |
| 58 | + } |
56 | 59 | } |
57 | | - } |
58 | 60 |
|
59 | | - return stringBuilder.length() == s.length() ? stringBuilder.toString() : ""; |
| 61 | + return stringBuilder.length() == s.length() ? stringBuilder.toString() : ""; |
| 62 | + } |
60 | 63 | } |
61 | 64 |
|
62 | 65 | } |
0 commit comments