Sentence Screen Fitting (Leetcod

2016-12-24  本文已影响0人  stepsma

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

int wordsTyping(vector<string>& 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.size(); i++){
            total_len += sentence[i].length()+1;
        }
        while(row <= rows){
            if(col >= 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;
    }
上一篇下一篇

猜你喜欢

热点阅读