Java solution with good description


  • 0
    S
    public int wordsTyping(String[] sentence, int rows, int cols) {
            // if i-th word starts the row then there will be wc[i] words in that column.
            int[] wc = new int[sentence.length]; // 
    
            for (int i = 0; i < sentence.length; i++) {
                wc[i] = getWordCount(sentence, i, cols);
            }
    
            int totalNumOfWords = 0;
            int index = 0;
    
            for (int r = 0; r < rows; r++) {
                totalNumOfWords = totalNumOfWords + wc[index];
                index = (wc[index] + index) % sentence.length;
            }
    
            return totalNumOfWords / sentence.length;
        }
    
        private int getWordCount(String[] sentence, int index, int cols) {
    
            int count = 0;
            int remCols = cols;
    
            while (sentence[index].length() <= remCols) {
                remCols = remCols - sentence[index].length() - 1; // subtract 1 for white space.
                index = (index + 1) % sentence.length;
                count++;
            }
    
            return count;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.