Sentence Screen Fitting

The problem is asking us to determine how many times a given sentence can fit on a screen of given rows and columns, keeping the order of words unchanged and considering that a word cannot be split into two lines.

Here’s a step-by-step solution:

  1. Calculate Sentence Length: Find the total length of the sentence including spaces between the words.
  2. Iterate Through Rows: Iterate through the rows of the screen and calculate how many characters can fit in each row, adjusting for spaces and ensuring that words are not split.
  3. Calculate Sentence Count: Calculate the number of times the sentence appears on the screen.

Here’s the code implementation for the above approach:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int:
        sentence_length = sum(len(word) + 1 for word in sentence) # Including space after each word
        sentence_str = ' '.join(sentence) + ' ' # Make a string with space after each word
        start = 0 # Starting position of the current line

        # Iterate through the rows
        for _ in range(rows):
            start += cols # Add the number of columns to the start

            # If the current position is at the end of a word or space
            if sentence_str[start % sentence_length] == ' ':
                start += 1
            else:
                # If the current position is inside a word, move back to the previous space
                while start > 0 and sentence_str[(start - 1) % sentence_length] != ' ':
                    start -= 1

        # Number of times the sentence appears on the screen
        return start // sentence_length

This solution respects the constraints that a word cannot be split into two lines and that a single space must separate two consecutive words in a line. It efficiently calculates the number of times the given sentence can be fitted on the screen.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int:
        s = " ".join(sentence) + " "
        start = 0
        l = len(s)

        for i in range(rows):
            start += cols
            if s[start % l] == ' ':
                start += 1
            else:
                while start > 0 and s[(start - 1) % l] != ' ':
                    start -= 1

        return start // len(s)