File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } s
3
+ * @param {number } repeatLimit
4
+ * @return {string }
5
+ */
6
+ var repeatLimitedString = function ( s , repeatLimit ) {
7
+ const a = 'a' . charCodeAt ( 0 )
8
+ const ch = Array ( 26 ) . fill ( 0 )
9
+ for ( let e of s ) {
10
+ const idx = e . charCodeAt ( 0 )
11
+ ch [ idx - a ] ++
12
+ }
13
+ let res = '' , last = ''
14
+ while ( true ) {
15
+ let len = res . length
16
+ let h = false
17
+ for ( let i = 25 ; i >= 0 ; i -- ) {
18
+ if ( ch [ i ] >= repeatLimit && res [ res . length - 1 ] !== String . fromCharCode ( a + i ) ) {
19
+
20
+ res += String . fromCharCode ( a + i ) . repeat ( repeatLimit )
21
+ ch [ i ] -= repeatLimit
22
+
23
+ if ( ch [ i ] ) {
24
+ for ( let j = i - 1 ; j >= 0 ; j -- ) {
25
+ if ( ch [ j ] ) {
26
+ res += String . fromCharCode ( a + j )
27
+ ch [ j ] --
28
+ break
29
+ }
30
+ }
31
+ break
32
+ }
33
+
34
+ } else if ( ch [ i ] > 0 && res [ res . length - 1 ] !== String . fromCharCode ( a + i ) ) {
35
+
36
+ res += String . fromCharCode ( a + i ) . repeat ( ch [ i ] )
37
+ ch [ i ] = 0
38
+ break
39
+ }
40
+ }
41
+ if ( len === res . length ) break
42
+ }
43
+
44
+
45
+ return res
46
+ } ;
You can’t perform that action at this time.
0 commit comments