- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1405.java
71 lines (65 loc) · 2.2 KB
/
_1405.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
packagecom.fishercoder.solutions.secondthousand;
importjava.util.PriorityQueue;
publicclass_1405 {
publicstaticclassSolution1 {
publicStringlongestDiverseString(inta, intb, intc) {
PriorityQueue<Tuple> maxHeap = newPriorityQueue<>((x, y) -> y.count - x.count);
if (a > 0) {
maxHeap.offer(newTuple('a', a));
}
if (b > 0) {
maxHeap.offer(newTuple('b', b));
}
if (c > 0) {
maxHeap.offer(newTuple('c', c));
}
StringBuildersb = newStringBuilder();
while (maxHeap.size() > 1) {
Tupleone = maxHeap.poll();
if (one.count >= 2) {
sb.append(one.c);
sb.append(one.c);
one.count -= 2;
} else {
sb.append(one.c);
one.count--;
}
Tupletwo = maxHeap.poll();
if (two.count >= 2 && one.count < two.count) {
sb.append(two.c);
sb.append(two.c);
two.count -= 2;
} else {
sb.append(two.c);
two.count--;
}
// only after the above two poll() calls, then do below:
if (one.count > 0) {
maxHeap.offer(one);
}
if (two.count > 0) {
maxHeap.offer(two);
}
}
if (!maxHeap.isEmpty()) {
if (sb.length() == 0 || sb.charAt(sb.length() - 1) != maxHeap.peek().c) {
if (maxHeap.peek().count >= 2) {
sb.append(maxHeap.peek().c);
sb.append(maxHeap.peek().c);
} else {
sb.append(maxHeap.peek().c);
}
}
}
returnsb.toString();
}
classTuple {
charc;
intcount;
publicTuple(charc, intcount) {
this.c = c;
this.count = count;
}
}
}
}