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