File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } S
3
+ * @return {string }
4
+ */
5
+ function reorganizeString ( S ) {
6
+ const map = { }
7
+ const cArr = S . split ( '' )
8
+ for ( let c of cArr ) {
9
+ let count = ( map [ c ] || 0 ) + 1
10
+ // impossible to form a solution
11
+ if ( count > ( S . length + 1 ) / 2 ) {
12
+ return ''
13
+ }
14
+ map [ c ] = count
15
+ }
16
+
17
+ const pq = [ ]
18
+ for ( let c of Object . keys ( map ) ) {
19
+ pq . push ( [ c , map [ c ] ] )
20
+ }
21
+ pq . sort ( ( a , b ) => b [ 1 ] - a [ 1 ] )
22
+
23
+ // build the result
24
+ let sb = ''
25
+ while ( pq . length > 0 ) {
26
+ let first = pq . shift ( )
27
+ if ( sb . length === 0 || first [ 0 ] !== sb . charAt ( sb . length - 1 ) ) {
28
+ sb += first [ 0 ]
29
+ if ( -- first [ 1 ] > 0 ) {
30
+ pq . push ( first )
31
+ }
32
+ } else {
33
+ let second = pq . shift ( )
34
+ sb += second [ 0 ]
35
+ if ( -- second [ 1 ] > 0 ) {
36
+ pq . push ( second )
37
+ }
38
+ pq . push ( first )
39
+ }
40
+ pq . sort ( ( a , b ) => b [ 1 ] - a [ 1 ] )
41
+ }
42
+
43
+ return sb
44
+ }
You can’t perform that action at this time.
0 commit comments