File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -36,3 +36,41 @@ const reorganizeString = function(S) {
36
36
}
37
37
return parts . join ( '' ) ;
38
38
} ;
39
+
40
+ // another
41
+
42
+ /**
43
+ * @param {string } s
44
+ * @return {string }
45
+ */
46
+ const reorganizeString = function ( s ) {
47
+ const arr = Array ( 26 ) . fill ( 0 ) , a = 'a' . charCodeAt ( 0 )
48
+ for ( let ch of s ) arr [ ch . charCodeAt ( 0 ) - a ] ++
49
+ let max = 0 , idx = - 1
50
+ for ( let i = 0 ; i < 26 ; i ++ ) {
51
+ if ( arr [ i ] > max ) {
52
+ max = arr [ i ]
53
+ idx = i
54
+ }
55
+ }
56
+ const n = s . length
57
+ const res = Array ( n )
58
+ if ( max > ( n + 1 ) / 2 ) return ''
59
+
60
+ let i = 0
61
+ while ( arr [ idx ] > 0 ) {
62
+ res [ i ] = String . fromCharCode ( a + idx )
63
+ i += 2
64
+ arr [ idx ] --
65
+ }
66
+
67
+ for ( let j = 0 ; j < 26 ; j ++ ) {
68
+ while ( arr [ j ] ) {
69
+ if ( i >= n ) i = 1
70
+ res [ i ] = String . fromCharCode ( a + j )
71
+ i += 2
72
+ arr [ j ] --
73
+ }
74
+ }
75
+ return res . join ( '' )
76
+ } ;
You can’t perform that action at this time.
0 commit comments