File tree 2 files changed +43
-0
lines changed
2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change 581
581
764|[ Largest Plus Sign] ( ./0764-largest-plus-sign.js ) |Medium|
582
582
765|[ Couples Holding Hands] ( ./0765-couples-holding-hands.js ) |Hard|
583
583
766|[ Toeplitz Matrix] ( ./0766-toeplitz-matrix.js ) |Easy|
584
+ 767|[ Reorganize String] ( ./0767-reorganize-string.js ) |Medium|
584
585
783|[ Minimum Distance Between BST Nodes] ( ./0783-minimum-distance-between-bst-nodes.js ) |Easy|
585
586
784|[ Letter Case Permutation] ( ./0784-letter-case-permutation.js ) |Medium|
586
587
790|[ Domino and Tromino Tiling] ( ./0790-domino-and-tromino-tiling.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 767. Reorganize String
3
+ * https://leetcode.com/problems/reorganize-string/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given a string s, rearrange the characters of s so that any two adjacent characters are
7
+ * not the same.
8
+ *
9
+ * Return any possible rearrangement of s or return "" if not possible.
10
+ */
11
+
12
+ /**
13
+ * @param {string } s
14
+ * @return {string }
15
+ */
16
+ var reorganizeString = function ( s ) {
17
+ const charCount = new Map ( ) ;
18
+ for ( const char of s ) {
19
+ charCount . set ( char , ( charCount . get ( char ) || 0 ) + 1 ) ;
20
+ }
21
+
22
+ const maxHeap = [ ...charCount . entries ( ) ]
23
+ . sort ( ( a , b ) => b [ 1 ] - a [ 1 ] ) ;
24
+
25
+ if ( maxHeap [ 0 ] [ 1 ] > Math . ceil ( s . length / 2 ) ) {
26
+ return '' ;
27
+ }
28
+
29
+ const result = [ ] ;
30
+ let index = 0 ;
31
+
32
+ while ( maxHeap . length ) {
33
+ const [ char , count ] = maxHeap . shift ( ) ;
34
+ for ( let i = 0 ; i < count ; i ++ ) {
35
+ result [ index ] = char ;
36
+ index += 2 ;
37
+ if ( index >= s . length ) index = 1 ;
38
+ }
39
+ }
40
+
41
+ return result . join ( '' ) ;
42
+ } ;
You can’t perform that action at this time.
0 commit comments