Sunday, June 18, 2017

418. Sentence Screen Fitting

Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen.
Note:
  1. A word cannot be split into two lines.
  2. The order of words in the sentence must remain unchanged.
  3. Two consecutive words in a line must be separated by a single space.
  4. Total words in the sentence won't exceed 100.
  5. Length of each word is greater than 0 and won't exceed 10.
  6. 1 ≤ rows, cols ≤ 20,000.
Example 1:
Input:
rows = 2, cols = 8, sentence = ["hello", "world"]

Output: 
1

Explanation:
hello---
world---

The character '-' signifies an empty space on the screen.
Example 2:
Input:
rows = 3, cols = 6, sentence = ["a", "bcd", "e"]

Output: 
2

Explanation:
a-bcd- 
e-a---
bcd-e-

The character '-' signifies an empty space on the screen.
Example 3:
Input:
rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"]

Output: 
1

Explanation:
I-had
apple
pie-I
had--

The character '-' signifies an empty space on the screen.



Solution:

Given a word in the input array, and if it is the start of the current line, we can calculate:

1. How many times this sentence can be fit into this line?

2, Which word will be the start of the next line?

After pre-computing the above states, we can easily calculate how many time can this sentence fit into the given rows and columns.



Code:


public class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        int[] next = new int[sentence.length];
        int[] times = new int[sentence.length];
        for (int i = 0; i < sentence.length; i++) {
            int curr = i;
            int col = 0;
            int time = 0;
            // Adding up words cannot exceeds cols.
            while (col + sentence[curr].length() <= cols) {
                // Add this word and a space.
                col = col + sentence[curr++].length() + 1;
                // We reach the end of the word in a sentence.
                if (curr == sentence.length) {
                    curr = 0;
                    time++;
                }
            }
            next[i] = curr;
            times[i] = time;
        }
        
        int res = 0;
        int curr = 0;
        for (int i = 0; i < rows; i++) {
            res += times[curr];
            curr = next[curr];
        }
        return res;
    }
}