链接:http://www.lintcode.com/zh-cn/problem/sentence-screen-fitting/
Given a rows x cols
screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen.
注意事项
- 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 is greater than 0 and won't exceed
10
. 1 ≤ rows, cols ≤ 20,000
.
您在真实的面试中是否遇到过这个题?
Yes
样例
Given rows = 2
, cols = 8
, sentence = ["hello", "world"]
, retrun 1
.
Explanation:
hello---
world---
The character '-' signifies an empty space on the screen.
Given rows = 3
, cols = 6
, sentence = ["a", "bcd", "e"]
, return 2
.
Explanation:
a-bcd-
e-a---
bcd-e-
The character '-' signifies an empty space on the screen.
Given rows = 4
, cols = 5
, sentence = ["I", "had", "apple", "pie"]
, return 1
.
Explanation:
I-had
apple
pie-I
had--
The character '-' signifies an empty space on the screen.
思路
这道题给我们了一个句子,由若干个单词组成,然后给我们了一个空白屏幕区域,让我们填充单词,前提是单词和单词之间需要一个空格隔开,而且单词不能断开,如果当前行剩余位置放下不下某个单词,则必须将该单词整个移动到下一行。我刚开始想的是便利句子,每个单词分别处理,但是这种做法很不高效,因为有可能屏幕的宽度特别大,而单词可能就一两个,那么我们这样遍历的话就太浪费时间了,应该直接用宽度除以句子加上空格的长度之和,可以快速的得到能装下的个数。下面这种方法设计的很巧妙,思路是用totallen变量来记录下能装下的句子的总长度(在totallen 里面,句子和句子之间仅相差一个空格),最后除以一个句子的长度,就可以得到个数。而句子的总长度的求法时要在每个单词后面加上一个空格,我们遍历屏幕的每一行,然后每次totallen都加上宽度,然后看all[totallen%len]是否为空格,是的话就totallen加1,这样做的好处是可以处理末尾是没有空格的情况,比如宽度为1,只有一个单词a,那么我们都知道是这样放的 a ,totallen变为1,len是2,all[totallen%len]是空格,所以totallen自增1,变成2,这样我们用totallen/len就知道能放下几个了。对于all[totallen%len]不为空格的情况,如果all[(totallen-1)%len]也不为空格,那么totallen就自减1,进行while循环,直至其为空格为止。
class Solution {
public:
/**
* @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
*/
int wordsTyping(vector<string> &sentence, int rows, int cols) {
// Write your code here
string all="";
for(auto s:sentence)
all+=(s+" ");
int totallen=0;
int len=all.size();
for(int i=0;i<rows;i++)
{
totallen+=cols;
if(all[totallen%len]==' ')
{
totallen++;
}
else
{
while(totallen>0 && all[(totallen-1)%len]!=' ')
{
totallen--;
}
}
}
return totallen/len;
}
};