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.
    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.

思路
假设string是无限循环下去的,需要记录所有row走完会move到哪里。用start指针的值记录一共在screen上有多少字符。最后通过start / sentence length即可知道一共能打印下多少个sentence。

具体包含以下步骤:

  1. 先把sentence连起来,然后摊平。例如:[“abc”, “de”, “f”],连成sentence是”abc de f “,设想这个sentence无限循环,就是”abc de f abc de f abc de f abc…”
  2. 用start pointer记录每一行的start,每多一个row,把pointer往后移动cols个。
  3. 移动pointer时两种情况需要处理一下:
    • 一行的开头刚好是space,start指针直接+1,即remove一个space
    • 一行的开头刚好是一个word的中间,start需要退回到该word的开头,即在上一行增加一些space。
class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        String allSentence = "";
            
        //1. reorganized the sentence using " "
        for (String word : sentence) {
            allSentence += word + " ";
        }
        int len = allSentence.length();
        
        //2. calculate the start pointer
        int start = 0;
        
        for (int i = 0; i < rows; i++) {
            start = start + cols;
            if (allSentence.charAt(start % len) == ' ') {
                start++;
            } else {
                while (start > 0 && allSentence.charAt((start - 1) % len) != ' ') {
                    start--;
                }
            }
        }
        
        return start / len;
    }
}

你可能感兴趣的:(Sentence Screen Fitting)