05 August 2008
给定一个 row x cols 屏幕和一个表示为字符串列表的句子,返回给定的句子可以在屏幕上出现的次数。
句子中单词的顺序必须保持不变,一个单词不能分成两行。一个空格必须分隔一行中的两个连续单词。
Example 1:
1
2
3
4
5
6
Input: sentence = ["hello","world"], rows = 2, cols = 8
Output: 1
Explanation:
hello---
world---
The character '-' signifies an empty space on the screen.
Example 2:
1
2
3
4
5
6
7
Input: sentence = ["a", "bcd", "e"], rows = 3, cols = 6
Output: 2
Explanation:
a-bcd-
e-a---
bcd-e-
The character '-' signifies an empty space on the screen.
这道题给了一个句子,由若干个单词组成,然后给我们了一个空白屏幕区域,让我们填充单词,前提是单词和单词之间需要一个空格隔开,而且单词不能断开,如果当前行剩余位置放不下某个单词,则必须将该单词整个移动到下一行。
DP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
static class CountState {
int index;
int count;
CountState(int index, int count) {
this.index = index;
this.count = count;
}
}
CountState countWords(int[] wordLength, int start, int cols, int idx) {
int count = 0;
for (int j = start; j + wordLength[idx % wordLength.length] <= cols; ) {
j += wordLength[idx % wordLength.length] + 1;
count = (++idx % wordLength.length == 0) ? count + 1 : count;
}
return new CountState(idx, count);
}
public int wordsTyping(String[] sentence, int rows, int cols) {
int index = 0;
int characters = 0;
int[] wordLength = new int[sentence.length];
for (int i = 0; i < sentence.length; ++i) {
wordLength[i] = sentence[i].length();
characters += wordLength[i] + 1;
}
int sentenceCount = cols / characters;
int start = characters * sentenceCount;
int count = sentenceCount * rows;
CountState[] dp = new CountState[sentence.length];
for (int i = 0; i < rows; ++i) {
int realIndex = index % sentence.length;
if (dp[realIndex] == null) {
dp[realIndex] = countWords(wordLength, start, cols, realIndex);
}
index = dp[realIndex].index;
count += dp[realIndex].count;
}
return count;
}
}
https://leetcode.com/problems/sentence-screen-fitting/discuss/90845/21ms-18-lines-Java-solution
1
2
3
4
5
6
7
8
class Solution {
public int wordsTyping(String[] sentence, int rows, int cols) {
String s = String.join(" ", sentence) + " ";
int[] offset = new int[s.length()];
IntStream.range(1, s.length()).forEach(i -> offset[i] = s.charAt(i) == ' ' ? 1 : offset[i - 1] - 1);
return IntStream.range(0, rows).reduce(0, (a, b) -> a + cols + offset[(a + cols) % s.length()]) / s.length();
}
}