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