方法一 个人方法 模拟:
把text字符串用空格符分隔成数组,数组长度-1就是原字符串中空格的数量,将数组中的单词都提取到words数组中,有了空格数量和单词数量就能计算出相邻单词间需要的空格数量,维护一个空字符串str,str先加上一个单词然后加上相应的空格数量,多余的空格放到字符串末尾
var reorderSpaces = function(text) {
text=text.split(' ')
let space = text.length-1,words=[]
for(let item of text){
if(item!=''){
words.push(item)
}
}
let n=Math.floor(space/(words.length-1))
let str='',blank=' '
for(let item of words){
str+=item
if(n<=space){
str+=blank.repeat(n)
space-=n
}else{
str+=blank.repeat(space)
space=0
}
}
if(space) {
str+=blank.repeat(space)
}
return str
};
消耗时间和内存情况: