|
1 | 1 | classSolution {
|
2 |
| -publicStringlongestDiverseString(inta,intb,intc) { |
3 |
| -PriorityQueue<int[]>priorityQueue =newPriorityQueue<>((o1,o2) ->o2[1] -o1[1]); |
4 |
| -if (a >0) { |
5 |
| -priorityQueue.add(newint[]{0,a}); |
6 |
| - } |
7 |
| -if (b >0) { |
8 |
| -priorityQueue.add(newint[]{1,b}); |
9 |
| - } |
10 |
| -if (c >0) { |
11 |
| -priorityQueue.add(newint[]{2,c}); |
12 |
| - } |
13 |
| -StringBuildersb =newStringBuilder("zz"); |
14 |
| -while (!priorityQueue.isEmpty()) { |
15 |
| -int[]temp = {-1, -1}; |
16 |
| -charpeekChar = (char) ('a' +priorityQueue.peek()[0]); |
17 |
| -if (peekChar ==sb.charAt(sb.length() -1) && |
18 |
| -peekChar ==sb.charAt(sb.length() -2)) { |
19 |
| -temp[0] =priorityQueue.peek()[0]; |
20 |
| -temp[1] =priorityQueue.peek()[1]; |
21 |
| -priorityQueue.poll(); |
22 |
| -if (priorityQueue.isEmpty()) { |
23 |
| -break; |
| 2 | +publicStringlongestDiverseString(inta,intb,intc) { |
| 3 | +PriorityQueue<LetterFrequencyPair>pq = |
| 4 | +newPriorityQueue<>((p,q) ->q.frequency() -p.frequency()); |
| 5 | +if (a >0) { |
| 6 | +pq.add(newLetterFrequencyPair('a',a)); |
| 7 | + } |
| 8 | +if (b >0) { |
| 9 | +pq.add(newLetterFrequencyPair('b',b)); |
| 10 | + } |
| 11 | +if (c >0) { |
| 12 | +pq.add(newLetterFrequencyPair('c',c)); |
24 | 13 | }
|
25 |
| - } |
26 |
| -peekChar = (char) ('a' +priorityQueue.peek()[0]); |
27 |
| -if (peekChar !=sb.charAt(sb.length() -1) || |
28 |
| -peekChar !=sb.charAt(sb.length() -2)) { |
29 |
| -int[]removed =priorityQueue.poll(); |
30 |
| -sb.append(peekChar); |
31 |
| -removed[1]--; |
32 |
| -if (removed[1] >0) { |
33 |
| -priorityQueue.add(removed); |
| 14 | +StringBuildersb =newStringBuilder(); |
| 15 | +while (!pq.isEmpty()) { |
| 16 | +LetterFrequencyPairremoved =pq.remove(); |
| 17 | +intfrequency =removed.frequency(); |
| 18 | +intresultLength =sb.length(); |
| 19 | +if (resultLength >=2 && |
| 20 | +sb.charAt(resultLength -1) ==removed.letter() && |
| 21 | +sb.charAt(resultLength -2) ==removed.letter()) { |
| 22 | +if (pq.isEmpty()) { |
| 23 | +break; |
| 24 | + } |
| 25 | +LetterFrequencyPairtemp =pq.remove(); |
| 26 | +sb.append(temp.letter()); |
| 27 | +if (temp.frequency() -1 >0) { |
| 28 | +pq.add(newLetterFrequencyPair(temp.letter(),temp.frequency() -1)); |
| 29 | + } |
| 30 | + }else { |
| 31 | +sb.append(removed.letter()); |
| 32 | +frequency--; |
| 33 | + } |
| 34 | +if (frequency >0) { |
| 35 | +pq.add(newLetterFrequencyPair(removed.letter(),frequency)); |
| 36 | + } |
34 | 37 | }
|
35 |
| - } |
36 |
| -if (temp[0] != -1) { |
37 |
| -priorityQueue.add(temp); |
38 |
| - } |
| 38 | +returnsb.toString(); |
39 | 39 | }
|
40 |
| -returnsb.substring(2).toString(); |
41 |
| - } |
| 40 | + |
| 41 | +privaterecordLetterFrequencyPair(charletter,intfrequency) {} |
42 | 42 | }
|