LeetCode - Sentence Screen Fitting

null00
2 min readAug 13, 2021

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: sentence = ["hello","world"], rows = 2, cols = 8
Output: 1
Explanation:
hello---
world---
The character '-' signifies an empty space on the screen.

Example 2:

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.

Example 3:

Input: sentence = ["i","had","apple","pie"], rows = 4, cols = 5
Output: 1
Explanation:
i-had
apple
pie-i
had--
The character '-' signifies an empty space on the screen.

Constraints:

  • 1 <= sentence.length <= 100
  • 1 <= sentence[i].length <= 10
  • sentence[i] consists of lowercase English letters.
  • 1 <= rows, cols <= 2 * 104

Solution1:

    public int wordsTyping(String[] sentence, int rows, int cols) {
String s = String.join(" ", sentence) + " ";
int len = s.length();
int start = 0;
for (int i = 0; i < rows; ++i) {
start += cols;
if (s.charAt(start % len) == ' ') {
++start;
} else {
while (start > 0 && s.charAt((start-1)%len) !=' ') {
--start;
}
}
}
return start / s.length();
}

Solution2:

    public int wordsTyping(String[] sentence, int rows, int cols) {
String s = String.join(" ", sentence) + " ";
int len = s.length();
int[] map = new int[len];
for (int i=1;i<len;++i){
map[i]=s.charAt(i)==' '?1:(map[i-1]-1);
}
int start=0;
for (int i=0;i<rows;++i){
start += cols;
start += map[start%len];
}
return start/len;
}

--

--