418. Sentence Screen Fitting π
Description
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 * 104
Solutions
Solution 1
Thinking
Testing word by word on each row is clumsy: there can be \(10^4\) rows and the sentence repeats.
Join the words with a trailing space into a cyclic string \(s\), and let \(\textit{cur}\) be the number of characters already covered. Each row adds \(\textit{cols}\): if that landing is a space, the row ended on a word boundary and we advance one more; otherwise we rewind to the previous space, i.e. push the unfinished word to the next row.
The number of full sentences is \(\lfloor \textit{cur}/|s| \rfloor\). The trailing space encodes the mandatory gap, and the rewind forbids splitting a word.
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |