418. Sentence Screen Fitting

45 阅读1分钟

image.png

image.png

方法

记录每行剩余space

class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        int wordIdx = 0, rowIdx = 0;
        int times = 0;
        int space = cols; // empty space avaliable in each row
        while (rowIdx < rows) {
            if (sentence[wordIdx].length() <= space) {
                space -= sentence[wordIdx].length();
                space--; // for - to seperate
                wordIdx++;
            } else {
                rowIdx++; // 该行空格放不下,换下一行
                space = cols;
            }
            if (wordIdx == sentence.length) {
                times++;
                wordIdx = 0;
            }
        }
        return times;
    }
}