Accepted JavaScript solution


  • 0
    var wordsTyping = function(sentence, rows, cols) {
        const len = sentence.reduce((count, word) => count + word.length, 0) + sentence.length - 1;
        let pos = { r: 0, c: 0, w: 0 };
    
        // Find out when the rows begin to repeat...
        while (pos.c === 0 && pos.w === 0 || pos.c % cols > 0 || pos.w % sentence.length > 0) {
            addWords(pos, sentence, len, cols);
            // ...or we hit the end of the screen
            if (pos.r === rows) return Math.floor(pos.w / sentence.length);
        }
    
        // We're done with the repeating rows...
        const res = Math.floor(rows / pos.r) * Math.floor(pos.w / sentence.length);
    
        // ...but we need to walk through the remaining rows
        rows %= pos.r;
        pos = { r: 0, c: 0, w: 0 };
        while (pos.r < rows) addWords(pos, sentence, len, cols);
    
        return res + Math.floor(pos.w / sentence.length);
    };
    
    function addWords(pos, sentence, len, cols) {
        const c = pos.c % cols;
        const word = sentence[pos.w % sentence.length];
    
        if (c === 0 && len <= cols) {                    // a new row fits the sentence
            pos.c += len;
            pos.w += sentence.length;
        } else if (c > 0 && c + 1 + len <= cols) {       // one or more sentences fit
            const times = Math.floor((cols - c) / (1 + len));
            pos.c += times * (1 + len);
            pos.w += times * sentence.length;
        } else if (c + (c > 0) + word.length <= cols) {  // the next word fits
            pos.c += (c > 0) + word.length;
            pos.w++;
        } else {                                         // the next word doesn't fit
            pos.c += cols - c;
        }
    
        if (pos.c % cols === 0) pos.r++;
    }
    

    This isn't pretty, but I have to post my less attractive solutions too.


Log in to reply
 

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