問題描述
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;
}