LeetCode 418. Sentence Screen Fitting

原题链接在这里:https://leetcode.com/problems/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.

题解:

把原有的sentence用String s表示出来再加上空格. 看最后start能走到的位置除以s的长度取整就是能走几遍.

每行fill时正好fill到一个词结束, 那么当前点对应的就应该是空格. start指针向后移动一位到新的词的开头就好.

不然就是在一个词当中, 就需要往回移动start直到前一位指向了空格. 相当于screen这行剩下的位置用空格填补.

Time Complexity: O(rows * cols). 可能整行都放不下个词, start index回移了整行用时 O(cols). 一共rows行.

Space: O(s.length()).

AC Java:

 1 class Solution {
 2     public int wordsTyping(String[] sentence, int rows, int cols) {
 3         if(sentence == null || sentence.length == 0 || rows == 0 || cols == 0){
 4             return 0;
 5         }
 6         
 7         String s = String.join(" ", sentence) + " ";
 8         int len = s.length();
 9         
10         int start = 0;
11         for(int i = 0; i<rows; i++){
12             start += cols;
13             if(s.charAt(start%len) == ' '){
14                 start++;
15             }else{
16                 while(start>0 && s.charAt((start-1)%len)!=' '){
17                     start--;
18                 }
19             }
20         }
21         return start/len;
22     }
23 }

类似Text Justification.

posted @ 2017-09-27 15:42  Dylan_Java_NYC  阅读(380)  评论(0编辑  收藏  举报