LintCode: 889 屏幕句子适配

分析:直接采用暴力法解决,对于每一行,分析该行可以容纳的单词数,这涉及到列数与单词长度之间的大小关系。

public class Solution {
    /**
     * @param sentence: a list of string
     * @param rows: an integer
     * @param cols: an integer
     * @return: return an integer, denote times the given sentence can be fitted on the screen
     */
    public int wordsTyping(String[] sentence, int rows, int cols) {
        // Write your code here
        int[] len=new int[sentence.length];
        for(int i=0;i<sentence.length;i++) {
            len[i] = sentence[i].length();
            if(len[i]>cols)  //单词长度大于列数的情况
                return 0;
        }
        int row=0,count=0,index=0;
        while(row<rows){
            int col=0;
            while(col<cols){
                if(col+len[index]<=cols){
                    col=col+len[index]+1; //下一个单词开始时的列号
                    index++;
                }else{
                    col=cols;
                }
                if(index==sentence.length){ //开始下一个单词列表的循环
                    count++;
                    index=0;
                }
            }
            row++;
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_27139155/article/details/80447412