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

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。