30. Substring with Concatenation of All Words

class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> ret=new ArrayList<Integer>();
        if(words.length==0||words[0].length()==0||s.length()==0)
            return ret;
        int wlen=words[0].length();
        int tlen=wlen*words.length;
        Map<String, Queue<Integer>> map=new HashMap<String, Queue<Integer>>();
        for(int i=0;i<wlen;i++)
        {
          	map.clear();
            for(String w:words)
            {
                if(!map.containsKey(w))
                    map.put(w, new LinkedList<Integer>());
                map.get(w).add(-1);
            }
            int j=i;
            int k=i;
            while(k+wlen<=s.length())
            {
                String word=s.substring(k,k+wlen);
                if(!map.containsKey(word))
                    j=k+wlen;
                else
                {
                    int idx=map.get(word).poll();
                    if(idx>=j)
                        j=idx+wlen;
                    map.get(word).add(k);
                }
                k+=wlen;
                if(k-j==tlen)
                    ret.add(j);
            }
        }
        return ret;
    }
}

  

posted @ 2017-09-23 07:18  Weiyu Wang  阅读(130)  评论(0编辑  收藏  举报