JavaScript Implementation


  • 0

    JavaScript Solution

        
        var extraSpacesToAdd = maxWidth - currentLineLength;
        var extraSpacesToAddPerWord = 0;
        if (currentWordsToAdd.length > 1) {
            extraSpacesToAddPerWord = Math.floor(extraSpacesToAdd / (currentWordsToAdd.length-1));
        }
        var firstWordExtraSpace = extraSpacesToAdd - (extraSpacesToAddPerWord*(currentWordsToAdd.length-1));
        currentRow = "";
        for(var i = 0; i < currentWordsToAdd.length; i++) {
            var currentSpacesToAdd = "";
            if (i === 0) {
                //First item
                currentSpacesToAdd = " ".repeat(firstWordExtraSpace + extraSpacesToAddPerWord);
            } else if (i === currentWordsToAdd.length - 1 && i !== 0) {
                //Last Item doesnt have extra space at the end
            } else {
                currentSpacesToAdd = " ".repeat(extraSpacesToAddPerWord);
            }
            currentRow = currentRow + currentWordsToAdd[i] + currentSpacesToAdd;
        }
        return currentRow;
    }
    
    /**
     * @param {string[]} words
     * @param {number} maxWidth
     * @return {string[]}
     */
    var fullJustify = function(words, maxWidth) {
        var result = [];
        var currentWordsToAdd = [];
        var currentLineLength = 0;
        var currentRow = "";
        var extraSpacesToAdd = 0;
        var extraSpacesToAddPerWord =  0;
        var firstWordExtraSpace = 0;
        
        for(var wordIndex=0; wordIndex < words.length; wordIndex++) {
            var word = words[wordIndex];
            if (currentLineLength + word.length + currentWordsToAdd.length > maxWidth ) {
                currentRow = getFullyJustifiedRow(currentWordsToAdd, maxWidth, currentLineLength);
                result.push(currentRow);
                currentWordsToAdd = [];
                currentLineLength = 0;
            }
            currentWordsToAdd.push(word);
            currentLineLength += word.length;
        }
        currentRow = getFullyJustifiedRow(currentWordsToAdd, maxWidth, currentLineLength);
        result.push(currentRow);
        return result;
        
    };```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.