# Why my code doesn't work

• My idea is to save the remain numbers of spaces in the current column into a HashMap, so that every time we meet the same situation, we can check with the hashmap.

The case ["a"] 10000, 10000 always give me Time Exceed Limitation. Can anyone provide any suggestion on how to optimize it? Thanks in advance!!

public class Solution {
public int wordsTyping(String[] sentence, int rows, int cols) {
if(sentence==null || sentence.length==0) return -1;
if(rows<=0 || cols<=0) return -1;
int maxCapacity = rows*cols;
HashMap<Integer, Integer> nextPosition = new HashMap<Integer, Integer>();
int idx = 0;//current position
int remain = cols;//remain how many spaces remain in current col
int time = 0;
while(idx<=maxCapacity){
int start = remain;//record current remain;
int startPosi = idx;
int idxj = 0;
if(nextPosition.containsKey(start)){
idx += nextPosition.get(start);
remain = cols - idx%cols;
time++;
continue;
}
while(idxj < sentence.length){
int strLen = sentence[idxj].length();
if(remain == strLen){
remain = cols;
idx += strLen;
}else if(remain > strLen){
remain = remain - strLen-1;
idx += strLen+1;
}else{
idx += remain;
remain = cols;
continue;
}
idxj++;
}
time++;
int difference = idx - startPosi;
nextPosition.put(start, difference);
}
return time-1;
}
}

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