Java. 34 lines. Comments. 84 ms.


  • 0
    H
    public class Solution {
        public int wordsTyping(String[] sentence, int rows, int cols) {
            
            
            int wordsUsed = 0; // to return (total number of words used) / (total number of words)    
            int wordIdx = 0; // index, indicating a word sequencially
            
            // get full length including "(word + delimiter) + (word + delimiter) + ... +(word + delimiter)". 
            // Ex: "Hello-World-". 
            int fullLength = 0;
            for(String str : sentence){
                if(str.length()>cols) return 0; //if length of a word is bigger than col size, return 0.
                fullLength+=str.length();
                fullLength+=1;
            }
            
            // check every row
            for(int i=0; i<rows; i++){
                int space = cols; // get reaminig space
                int repeat = space/fullLength; // check how many time the full sentence can be appeared.
                
                space -= repeat*fullLength; // fill whole sentence in a row, and deduct space.
                wordsUsed+= repeat*sentence.length; // count words that are used
                
                while(space>0 && sentence[wordIdx].length()<=space){ //if space is remained, 
                    space -= sentence[wordIdx++].length(); //fill a word in the row.
                    if(space>=1) space -= 1; // add delimiter
                    wordIdx %= sentence.length; //update word index
                    wordsUsed++; // count the total number of words used
                }
            }
            return wordsUsed/sentence.length;
        }
    }
    

Log in to reply
 

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