java solution with hashmap


  • 0
    I
    public int wordsTyping(String[] sentence, int rows, int cols) {
        int rowsc=0;
        int index=0;
        int res=0;
        int cur;
        HashMap<Integer,LinkedList<Integer>> map = new HashMap<>();
        while (rowsc<rows){
            rowsc++;
            cur=0;
            if (map.containsKey(index)){
                LinkedList<Integer> list = map.get(index);
                index=list.get(0);
                res+=list.get(1);
            }
            else{
                int init = index;
                int initres=res;
                while (cur<cols){
                    if (cur+sentence[index].length()<=cols ){
                        cur+=sentence[index].length();
                        cur+=1;
                        index++;
                        if (index==sentence.length) {index=0;res++;}
                    }
                    else
                        break;
                }
                LinkedList<Integer> list = new LinkedList<>();
                list.add(index); list.add(res-initres);
                map.put(init,list);
            }
            
        }
        return res;
    }

Log in to reply
 

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