Sentence Screen Fitting Problem
Description
LeetCode Problem 418.
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 <= 1001 <= sentence[i].length <= 10sentence[i]consists of lowercase English letters.1 <= rows, cols <= 2 * 10^4
Solution
Approach: Walk Along the Repeated Sentence
Placing words one by one is slow when the screen is large (up to 2 · 104 rows of 2 · 104 columns). Instead, look at the text the screen shows as one long string: the sentence with a space after every word, repeated forever. With s = "a bcd e " for Example 2, the screen reads s s s ... from left to right and top to bottom, with each row break swallowing a space.
Keep cur, the number of characters of that endless text placed so far (position cur in it is s[cur % len(s)]). For each row:
- Assume the row is filled completely:
cur += cols. - If the character at
curis a space, the row ended exactly at the end of a word. The space does not need a cell on the screen, so skip it:cur += 1. - Otherwise a word would be cut in half. Move
curback until the character before it is a space, which pushes the cut word to the next row.
After all rows, every len(s) characters placed is one full copy of the sentence, so the answer is cur / len(s).
Step 3 moves back at most 10 characters, since that is the longest word. If a word is longer than cols, step 3 brings cur all the way back to the start of the row. The same thing then happens on every row, nothing is ever placed, and the answer is 0.
Complexity: O(rows · L + total length of the words) time, where L ≤ 10 is the longest word. O(total length of the words) space for s.
class Solution:
def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int:
s = " ".join(sentence) + " " # the sentence repeats forever: s, s, s, ...
m = len(s)
cur = 0 # characters of the endless text placed so far
for _ in range(rows):
cur += cols # fill the row
if s[cur % m] == " ":
cur += 1 # the row ends at a word boundary; the space is not needed on the screen
else:
while cur > 0 and s[(cur - 1) % m] != " ":
cur -= 1 # a word is cut: move it to the next row
return cur // m