Sentence Screen Fitting (Leetcode 418)

G家的一道题,属于会者不难的那种,一个要点是remaining column要从 total column 往下减,而不是从 0 往上加。同时,要用除和取mod,来节省时间。

int wordsTyping(vector& sentence, int rows, int cols) {
        if(sentence.empty()) return rows * cols;
        
        int row = 1, col = cols, idx = 0, cnt = 0;
        int total_len = 0;
        for(int i=0; i= sentence[idx].length()){
                col = col - sentence[idx].length();
                if(col > 0) col--;
                if(++idx == sentence.size()){
                    cnt += (1 + col/total_len);
                    col = col % total_len;
                    idx = 0;
                }
            }else{
                row++; col = cols;
            }
        }
        return cnt;
    }

你可能感兴趣的:(Sentence Screen Fitting (Leetcode 418))