LeetCode 418. Sentence Screen Fitting

来源:互联网 发布:ps命令详解 linux 编辑:程序博客网 时间:2024/06/12 21:01

Given a rows x cols screen and a sentence represented by a list of words, find how many times the given sentence can be fitted on the screen.

Note:

A word cannot be split into two lines.
The order of words in the sentence must remain unchanged.
Two consecutive words in a line must be separated by a single space.
Total words in the sentence won’t exceed 100.
Length of each word won’t exceed 10.
1 ≤ rows, cols ≤ 20,000.

Example 1:

Input:
rows = 2, cols = 8, sentence = [“hello”, “world”]

Output:
1

Explanation:
hello—
world—

The character ‘-’ signifies an empty space on the screen.

Example 2:

Input:
rows = 3, cols = 6, sentence = [“a”, “bcd”, “e”]

Output:
2

Explanation:
a-bcd-
e-a—
bcd-e-

The character ‘-’ signifies an empty space on the screen.

Example 3:

Input:
rows = 4, cols = 5, sentence = [“I”, “had”, “apple”, “pie”]

Output:
1

Explanation:
I-had
apple
pie-I
had–

The character ‘-’ signifies an empty space on the screen.

s思路1:
1. 参考了http://www.cnblogs.com/grandyang/p/5975426.html
2. 自己也思考了下,肯定不能一个单词一个单词来放,太低效率。注意到,这类题,涉及到两个对象,一是有单词组成的句子,另一个是2维矩阵。要求是把句子放进矩阵里,计算可以放进去多少同样的句子?这就容易误导我们,认为方法就是去找每句话在矩阵中结束的位置坐标。除此之外,还可以反过来思考,根据矩阵的尺寸,找到每行开始坐标对应的完整句子(包括空格)中的位置,即:两种方法比较如下:

普通做法 think from the opposite angle 把一句话完整放进矩阵中,找矩阵中位置坐标。 句子是固定的,但每句话在矩阵中开始、结束坐标都不同 每一行可以放多少句子。判断每一行开始位置 对应句子中的坐标。 一句话可能夸越多行多列,而且要找两个参数(行、列)。比较复杂 只需要确定在每行开始位置对应的句子中的单词。 只需要确定一个参数的值。

3. 具体做法:先组成句子,由给定的word+空格组成;在每一行开始都加上这一行的长度,得到总的长度数,最后再将总的长度除以每句话的长度就可以得到可以装下的句子数量!这里,要考虑两个特殊情况,都是因为边界引起的:在每行开始的位置,如果总长度%每句长度的结果刚好是一个句子的空格位置,那么可以把后面的句子都往前挪动一个位置以期望放得更多的句子,因为规定每行开始不能有空格,例如:
句子: a-bcd-e- (8个字符)
矩阵:

a b c d e a b c d e

第二行开始的总坐标=0+5, sentence[5]=空格,就需要把后面的单词都往前挪一位,即:

a b c d e a b c d e

这种情况在数学上(或代码上)可以把总坐标+1来模拟。

第二种情况是:单词不允许break,夸越两行。所以如果每行开头不是空格,我们还需要判断(总长度-1)%每句长度的位置是否是空格,不是空格,我们就要浪费一个位置,即:多一个位置放空格,如上表。这种情况在数学上(或代码上)可以把总坐标-1来模拟。

//方法1:int wordsTyping(vector<string>& sentence, int rows, int cols) {    //    string withspace="";//""代表string    for(auto&word:sentence) withspace+=(word+"");//""代表string    int start=0,len=withspace.size();    for(int i=0;i<rows;i++){        start+=cols;        if(withspace[start%len]==' ')//每行开头不能有空格//' '代表char            start++;        else{            while(start>0&&withspace[(start-1)%len]!=' ')//每个单词不能break//' '代表char                start--;        }    }    return start/len;}
0 0
原创粉丝点击