美文网首页
Sentence Screen Fitting (Leetcod

Sentence Screen Fitting (Leetcod

作者: stepsma | 来源:发表于2016-12-24 00:27 被阅读0次

    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;
        }
    

    相关文章

      网友评论

          本文标题:Sentence Screen Fitting (Leetcod

          本文链接:https://www.haomeiwen.com/subject/awrlvttx.html