Skip to content

Commit 822d7d3

Browse files
authored
Create 1592-rearrange-spaces-between-words.js
1 parent 702004f commit 822d7d3

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {string} text
3+
* @return {string}
4+
*/
5+
const reorderSpaces = function(text) {
6+
let sc = 0
7+
for(let i = 0, len = text.length; i < len; i++) {
8+
if(text[i] === ' ') sc++
9+
}
10+
const arr = text.split(' ').filter(e => e!= '')
11+
const num = arr.length - 1
12+
const remain = num === 0 ? sc : sc % num
13+
const split = num === 0 ? 0 : Array( (sc / num) >> 0 ).fill(0).reduce((ac, el) => ac + ' ', '')
14+
let res = ''
15+
res = arr.join(split) + helper(remain)
16+
return res
17+
};
18+
19+
function helper(n) {
20+
let res = ''
21+
for(let i = 0; i < n; i++) res += ' '
22+
return res
23+
}

0 commit comments

Comments
 (0)