Java 49ms with map, easy understand version.


  • 0
    N
    public class Solution {
        public int wordsTyping(String[] sentence, int rows, int cols) {
            Map<Integer, Integer> maps = new HashMap<>();
            int len = sentence.length;
            int count = 0;
            int tmpCol = cols;
            int rowCount = 0;
            while(rows>0){
                if(tmpCol == cols && maps.containsKey(count%len)){
                    rowCount = count;
                    count+= maps.get(count%len);
                    rows--;
                    continue;
                }
                
                int tmpLen = sentence[count%len].length();
                if(cols < tmpLen) return 0;
                if(tmpCol < tmpLen){
                    tmpCol = cols;
                    if(!maps.containsKey(rowCount%len)){
                        maps.put(rowCount%len,count-rowCount);
                    }
                    rowCount = count;
                    rows--;
                }else{
                    count++;
                    tmpCol -= tmpLen+1;
                }
            }
            
            return count/len;
        }
    }
    
    

Log in to reply
 

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