File tree 1 file changed +70
-0
lines changed
1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change
1
+ //Longest Happy String
2
+ import java .util .PriorityQueue ;
3
+ class CountCharacter {
4
+ int count ;
5
+ char c ;
6
+
7
+ public CountCharacter (int ct ,char c ){
8
+ this .count =ct ;
9
+ this .c =c ;
10
+ }
11
+ }
12
+
13
+ class Med1405 {
14
+ public String longestDiverseString (int a , int b , int c ) {
15
+ //max heap
16
+ //3:c
17
+ PriorityQueue <CountCharacter > pq = new PriorityQueue <>((c1 ,c2 )-> c2 .count -c1 .count );
18
+
19
+ if (a >0 ){
20
+ pq .add (new CountCharacter (a ,'a' ));
21
+ }
22
+
23
+ if (b >0 ){
24
+ pq .add (new CountCharacter (b ,'b' ));
25
+ }
26
+
27
+ if (c >0 ){
28
+ pq .add (new CountCharacter (c ,'c' ));
29
+ }
30
+ //Input : a=1,b=1,c=7
31
+ //output: "ccaccbcc"
32
+ //{7:c,b:1,a:1}
33
+ StringBuilder sB = new StringBuilder ();
34
+ while (!pq .isEmpty ()){
35
+ CountCharacter ele = pq .poll ();
36
+
37
+ int count = ele .count ;
38
+ char c1 =ele .c ;
39
+ //three character rule will happen if we add c
40
+ if (sB .length ()>=2 && sB .charAt (sB .length ()-1 )==c1 && sB .charAt (sB .length ()-2 )==c1 ){
41
+ if (pq .isEmpty ()){
42
+ break ;
43
+ }
44
+ CountCharacter ele2 =pq .poll ();
45
+ int count2 =ele2 .count ;
46
+ char c2 =ele2 .c ;
47
+
48
+ count2 =count2 -1 ;
49
+ sB .append (c2 );
50
+
51
+ if (count2 >0 ){
52
+ pq .add (new CountCharacter (count2 ,c2 ));
53
+ }
54
+
55
+
56
+ }
57
+ else {
58
+ count =count -1 ;
59
+ sB .append (c1 );
60
+
61
+ }
62
+
63
+ if (count >0 ){
64
+ pq .add (new CountCharacter (count ,c1 ));
65
+ }
66
+
67
+ }
68
+ return sB .toString ();
69
+ }
70
+ }
You can’t perform that action at this time.
0 commit comments