| 1 | class Solution { |
| 2 | public String longestDiverseString(int a, int b, int c) { |
| 3 | String res = ""; |
| 4 | PriorityQueue<Pair<Integer, Character>> maxHeap = new PriorityQueue<>( |
| 5 | (i1, i2) -> i2.getKey() - i1.getKey()); |
| 6 | if (a > 0) { |
| 7 | maxHeap.add(new Pair<>(a, 'a')); |
| 8 | } |
| 9 | if (b > 0) { |
| 10 | maxHeap.add(new Pair<>(b, 'b')); |
| 11 | } |
| 12 | if (c > 0) { |
| 13 | maxHeap.add(new Pair<>(c, 'c')); |
| 14 | } |
| 15 | |
| 16 | while (!maxHeap.isEmpty()) { |
| 17 | Pair<Integer, Character> item = maxHeap.poll(); |
| 18 | Integer count = item.getKey(); |
| 19 | Character ch = item.getValue(); |
| 20 | if (res.length() > 1 |
| 21 | && ch.equals(res.charAt(res.length() - 1)) |
| 22 | && ch.equals(res.charAt(res.length() - 2))) { |
| 23 | if (maxHeap.isEmpty()) { |
| 24 | break; |
| 25 | } |
| 26 | Pair<Integer, Character> item2 = maxHeap.poll(); |
| 27 | Integer count2 = item2.getKey(); |
| 28 | Character ch2 = item2.getValue(); |
| 29 | res += ch2; |
| 30 | count2 -= 1; |
| 31 | if (count2 > 0) { |
| 32 | maxHeap.add(new Pair<>(count2, ch2)); |
| 33 | } |
| 34 | } else { |
| 35 | res += ch; |
| 36 | count -= 1; |
| 37 | } |
| 38 | if (count > 0) { |
| 39 | maxHeap.add(new Pair<>(count, ch)); |
| 40 | } |
| 41 | } |
| 42 | return res; |
| 43 | } |
| 44 | } |