Javascript Code
/**
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/
var fullJustify = function (words, maxWidth) {
let finalRes = []
let strArray = []
let charCount = 0
for (let word of words) {
if (word.length + strArray.length + charCount > maxWidth) {
finalRes.push(processArr(strArray, maxWidth))
strArray = []
charCount = 0
}
strArray.push(word)
charCount += word.length
}
finalRes.push(strArray.join(" ").padEnd(maxWidth, " "))
return finalRes
}
const processArr = (wordsArr, maxWidth) => {
if (wordsArr.length == 1) {
return wordsArr.join(" ").padEnd(maxWidth, " ")
}
let totalChars = wordsArr.reduce((sum, word) => sum + word.length, 0)
let totalSpaces = maxWidth - totalChars
let spaceSlots = wordsArr.length - 1
let spaceBetween = Math.floor(totalSpaces / spaceSlots)
let extraSpaces = totalSpaces % spaceSlots
let result = ""
for (let i = 0; i < wordsArr.length - 1; i++) {
result += wordsArr[i] + " ".repeat(spaceBetween + (i < extraSpaces ? 1 : 0))
}
result += wordsArr[wordsArr.length - 1]
return result
}
Top comments (0)