|
| 1 | +#!/usr/bin/python3 |
| 2 | +""" |
| 3 | +Given a rows x cols screen and a sentence represented by a list of non-empty |
| 4 | +words, find how many times the given sentence can be fitted on the screen. |
| 5 | +
|
| 6 | +Note: |
| 7 | +A word cannot be split into two lines. |
| 8 | +The order of words in the sentence must remain unchanged. |
| 9 | +Two consecutive words in a line must be separated by a single space. |
| 10 | +Total words in the sentence won't exceed 100. |
| 11 | +Length of each word is greater than 0 and won't exceed 10. |
| 12 | +1 ≤ rows, cols ≤ 20,000. |
| 13 | +Example 1: |
| 14 | +
|
| 15 | +Input: |
| 16 | +rows = 2, cols = 8, sentence = ["hello", "world"] |
| 17 | +
|
| 18 | +Output: |
| 19 | +1 |
| 20 | +
|
| 21 | +Explanation: |
| 22 | +hello--- |
| 23 | +world--- |
| 24 | +
|
| 25 | +The character '-' signifies an empty space on the screen. |
| 26 | +Example 2: |
| 27 | +
|
| 28 | +Input: |
| 29 | +rows = 3, cols = 6, sentence = ["a", "bcd", "e"] |
| 30 | +
|
| 31 | +Output: |
| 32 | +2 |
| 33 | +
|
| 34 | +Explanation: |
| 35 | +a-bcd- |
| 36 | +e-a--- |
| 37 | +bcd-e- |
| 38 | +
|
| 39 | +The character '-' signifies an empty space on the screen. |
| 40 | +Example 3: |
| 41 | +
|
| 42 | +Input: |
| 43 | +rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"] |
| 44 | +
|
| 45 | +Output: |
| 46 | +1 |
| 47 | +
|
| 48 | +Explanation: |
| 49 | +I-had |
| 50 | +apple |
| 51 | +pie-I |
| 52 | +had-- |
| 53 | +
|
| 54 | +The character '-' signifies an empty space on the screen. |
| 55 | +""" |
| 56 | +from typing import List |
| 57 | + |
| 58 | + |
| 59 | +class Solution: |
| 60 | + def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int: |
| 61 | + """ |
| 62 | + How many times to fit |
| 63 | +
|
| 64 | + Combine the words in to a string and wrap it around |
| 65 | + """ |
| 66 | + sentence = " ".join(sentence) + " " # unify the condition checking for the last word; tail will wrap with head with space |
| 67 | + i = 0 |
| 68 | + for r in range(rows): |
| 69 | + i += cols |
| 70 | + while sentence[i % len(sentence)] != " ": |
| 71 | + i -= 1 |
| 72 | + |
| 73 | + # now sentence[i] is " " |
| 74 | + i += 1 |
| 75 | + |
| 76 | + ret = i // len(sentence) |
| 77 | + return ret |
0 commit comments