LeetCode Sentence Screen Fitting
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Sentence Screen Fitting相关的知识,希望对你有一定的参考价值。
原题链接在这里:https://leetcode.com/problems/sentence-screen-fitting/description/
题目:
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:
- A word cannot be split into two lines.
- The order of words in the sentence must remain unchanged.
- Two consecutive words in a line must be separated by a single space.
- Total words in the sentence won‘t exceed 100.
- 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.
题解:
把原有的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 }
以上是关于LeetCode Sentence Screen Fitting的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Sentence Screen Fitting 调整屏幕上的句子
LeetCode 418. Sentence Screen Fitting
LeetCode 734. Sentence Similarity