ID | Title | Difficulty | |
---|---|---|---|
Loading... |
418. Sentence Screen Fitting
Medium
LeetCode
String, Dynamic Programming, Simulation
Problem
Given a rows x cols screen and a sentence represented as a list of strings, return the number of times the given sentence can be fitted on the screen.
The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.
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.
Code
- 每行都是以单词开始的!
class Solution {
public int wordsTyping(String[] sentence, int rows, int cols) {
int n = sentence.length;
int[] memo = new int[n];
// 一行以不同的单词为开始, 可以放几个单词
for(int i = 0; i < n; i++) {
int len = 0;
int wordNum = 0;
int index = i;
while(len + sentence[index % n].length() <= cols) {
len += sentence[index % n].length() + 1;
index++;
wordNum++;
}
memo[i] = wordNum;
}
// 一共可以放几个单词
int words = 0;
int index = 0;
for(int i = 0; i < rows; i++) {
words += memo[index];
index = (memo[index] + index) % n;
}
return words / n;
}
}
按 <- 键看上一题!
417. Pacific Atlantic Water Flow
按 -> 键看下一题!
419. Battleships in a Board