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.
Example
Example 1:
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.
Example 2:
Input: rows = 2, cols = 8, sentence = ["hello", "world"]
Output: 1
Explanation:
hello---
world---
The character '-' signifies an empty space on the screen.
Example 3:
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.
Notice
- 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
.
分析
这道题刚开始的时候一定想到的就是常规的解法,我们尝试向每一行里一个个的塞入单词,如果一个单词塞不进去了就另起一行,最终计算我们总共塞了多少个单词,然后除以sentence的长度就是最终结果。
这种解法在面临 cols >> setences总长度时,会超时。因为sentence组成的字符串的总长度远远小于cols,导致每一行都需要大量的时间。那么这一题能否一行一行的去处理呢?
其实最终我们求得结果时,是想知道最终遍历了多少次sentence,这样可以求得最终的次数。首先把sentences进行处理,将其利用空格做分隔符组成一个字符串s。那么我们就可以把这一题转化为我们处理完所有的rows和cols后,看看总共塞进去了多长的s的有效字符。对于每一行,直接尝试从当前在s中的偏移位置+ cols,如果此时的字符是空格,说明这一行恰好可以放入cols个字符串,但是由于我们的s都是以空格做分割的,我们需要把s后面的这个空格也统计进去,所以这一行我们就放了cols + 1个字符串;如果此时的字符是单词的字符,那么说明这一行没有放满,就向前寻找第一个是空格的位置,然后继续。
Code
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
int len = sentence.size();
string s;
for (int i = 0; i < sentence.size(); i ++)
{
s += sentence[i];
s += " ";
}
int sLen = s.size();
int start = 0;
for (int i = 0; i < rows; i ++)
{
start += cols;
if (s[start%sLen] == ' ')
{
start ++;
}
else
{
while (start > 0 && s[(start-1)%sLen] != ' ')
{
start --;
}
}
}
return start/sLen;
}
};
运行效率
Your submission beats 99.48% Submissions!