Trying to submit a code for Substring with Concatenation of All Words where I am getting Time Limit Exceeded.Please help me.


  • 0
    D

    public List<Integer> findSubstring(String s, String[] words) {
    ArrayList<Integer> result =new ArrayList<Integer>();
    int wslen = words.length;
    int slen = s.length();
    if(s.isEmpty() || wslen == 0 || slen < wslen * words[0].length())
    return result;
    int wlen = words[0].length();
    HashMap<String, Integer> subres = new HashMap<>(wslen);
    for(int i=0; i < wslen; i++){
    if(subres.containsKey(words[i]))
    subres.put(words[i], subres.get(words[i])+1);
    else
    subres.put(words[i], 1);
    }
    HashMap<String, Integer> subresult = new HashMap<String, Integer>(subres);
    int cals = slen-wlenwslen+1;
    for(int i=0; i< cals; i++){
    int j=0;
    for(;j<wslen;j++){
    int cal = i+j
    wlen;
    String substr = s.substring(cal, cal+wlen);
    if(!subres.containsKey(substr))
    break;
    else{
    subres.put(substr, subres.get(substr)-1);
    if(subres.get(substr) < 0)
    break;
    }
    }
    if(j == wslen)
    result.add(i);
    subres = new HashMap<String, Integer>(subresult);
    }
    return result;
    }


Log in to reply
 

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