MCPcopy Index your code
hub / github.com/neetcode-gh/leetcode / longestDiverseString

Method longestDiverseString

java/1405-longest-happy-string.java:2–43  ·  view source on GitHub ↗
(int a, int b, int c)

Source from the content-addressed store, hash-verified

1class 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}

Callers

nothing calls this directly

Calls 4

equalsMethod · 0.80
getKeyMethod · 0.45
addMethod · 0.45
isEmptyMethod · 0.45

Tested by

no test coverage detected