# 418 Sentence Screen Fitting

給一個句子String[] sentence,還有螢幕長寬 int rows, int cols。 問句子可以在螢幕上被印出幾次。印出時sentence中的單字要用空格隔開。

Concept: 用int start來記錄可以被印出合法(一個word不會被切斷)的char數。 跑過螢幕上的每個row,看每個row可放幾個char。 最後把start除以句子的總長即為完整印出的次數。

Pseudocode:

//String s = join all element in sentence, add " " at the end.
//int start to record how many valid characters from s have been put to our screen.
//int l = length of s
//for each row
//  add col to start
//  if the character at start % l is " "
//      this row can fit, add start by 1(skip the blank space, so the next row can start from a new word)
//  else, 
//      next word can't fit in this row, remove extra characters
//return start/l

Code:

public class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        String s = String.join(" ",sentence) +" ";
        int start = 0, l = s.length();
        for(int i=0; i<rows; i++){
            start += cols;
            if(s.charAt(start % l) == ' '){
                start++;
            }else{
                while(start > 0 && s.charAt((start-1) % l) != ' '){
                    start--;
                }
            }
        }
        return start/l;
    }
}

results matching ""

    No results matching ""