Verbose, Easy to Understand, JavaScript Solution


  • 0
    /**
     * @param {string[]} words
     * @param {number} maxWidth
     * @return {string[]}
     */
    var fullJustify = function(words, maxWidth) {
        if(maxWidth === 0) return words;
        
        var lines = [[]];
        var lineBudget = maxWidth+1;                // the remaining words in this line
        var line = 0;                               // the line we're on
        for(var i = 0; i < words.length; i++){
            var word = words[i];
            lineBudget -= word.length+1;
            if(lineBudget < 0){ // new line
                line++;
                lines.push([]);
                lineBudget = maxWidth+1;
                --i;
            } else {
                lines[line].push(word);
            }
        }
        
        var output = [];
        for(var i = 0; i < lines.length-1; i++){
            var line = lines[i];
            var freespace = getFreeSpace(line, maxWidth);
            output.push( justifyLine(line, freespace));
        }
        var lastLine = lines[lines.length-1];
        var lastFreespace = getFreeSpace(lastLine, maxWidth);
        output.push( leftAlign(lastLine, lastFreespace));
        return output;
    };
    
    function justifyLine( words, freespace ){
        // EDGE CASE: wordslength == 1
        if(words.length === 1){
            return words[0] + getWhiteSpace(freespace);
        }
        let spacesToFill = words.length - 1;
        let spaceLength = Math.floor(freespace / spacesToFill);
        let remainder = freespace % spacesToFill;
        
        let tokens = [];
        for(var i = 0; i < spacesToFill; i++){
            tokens.push(getWhiteSpace(spaceLength));
        }
        // add remainder
        for(var i = 0; i < remainder; i++){
            tokens[i] += " ";
        }
        tokens.push("");
        // merge words and tokens
        let out = "";
        for(var i = 0; i < words.length; i++){
            out += words[i];
            out += tokens[i];
        }
        return out;
    }
    
    function leftAlign(words, freespace){
        var out = words.join(" ");
        freespace -= words.length - 1;
        return out += getWhiteSpace(freespace);
    }
    
    function getWhiteSpace(len){
        let out = "";
        for(var i = 0; i < len; i++){
            out += " ";
        }
        return out;
    }
    
    function getFreeSpace(line, budget){
        var taken = 0;
        line.forEach((word)=>{
            taken += word.length;
        });
        return budget - taken;
    }
    

Log in to reply
 

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