问题描述
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.
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 is greater than 0 and 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.
简单翻译一下,有一个sentence数组,里面存若干个String, 现在要求在row行,col列中放这些String, 要求每个String不可分隔,每个String间至少要有一个分隔符(-),一行放不下的话就放下一行。问整个sentence数组能在row和col中完整出现几次。
思路:
看完题目首先想到straight force解法,按row进行loop,一个一个往row里面加,空间不够就跳下一行。
然而,当row=20000,col=20000是,系统报time exceed错误。仔细读题发现几个细节:
- 每行的开头必然是String,不是分隔符(-).
- sentence数组大小最大只有100。
- 对于每个String,它在该行的产生的结果都是一样的!
由此,我们另辟蹊径,把sentence中的每个String作为开头,存储一下在该行sentence重复了多少次,记录一下下一行的开头String应该是什么。有了这些数据,我们最后只需要进行一下简单的Loop,即可得到最后的result.
代码:
//best answer
public int wordsTyping(String[] sentence, int rows, int cols) {
int[] nextRowIndex = new int[sentence.length];
int[] times = new int[sentence.length];
for(int i=0;i<sentence.length;i++) {
int curLen = 0;
int index = i;
int time = 0;
while(curLen + sentence[index].length() <= cols) {
curLen += sentence[index++].length()+1;
if(index==sentence.length) {
index = 0;
time ++;
}
}
nextRowIndex[i] = index;
times[i] = time;
}
int res = 0;
int index = 0;
for(int i=0; i<rows; i++) {
res += times[index];
index = nextRowIndex[index];
}
return res;
}