给定一个单词数组和宽度,格式化文本,使其左右对其。
仔细判决即可,faster than 94%
创建n个空字符串,
Array(n).fill(' ').join('')
/**
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/
var fullJustify = function(words, maxWidth) {
var cur = 0
var sub = []
var res = []
var sp = 0
var mod = 0
for(var i = 0 ; i < words.length; i++){
if(cur + words[i].length <= maxWidth){
cur += words[i].length + 1
sub.push(words[i])
}else{
if(sub.length === 1){
sub[sub.length - 1] += Array(maxWidth - cur + 1).fill(' ').join('')
}else{
sp = parseInt((maxWidth - cur + 1) / (sub.length - 1))
mod = (maxWidth - cur + 1) % (sub.length - 1);
var j = 0
while(j < sub.length - 1){
if(mod > 0){
sub[j] += Array(sp + 1).fill(' ').join('')
mod--
}else{
sub[j] += Array(sp).fill(' ').join('')
}
j++
}
}
i--
res.push(sub.join(' '))
cur = 0
sub = []
}
}
if(cur.length !== 0){
sub[sub.length - 1] += Array(maxWidth - cur + 1).fill(' ').join('')
res.push(sub.join(' '))
}
return res
};