LeetCode 123 Substring with Concatenation of All Words


You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9].
(order does not matter).
分析:
辞書を検索して一致させる問題があるので、HashMapで辞書を保存する必要があります.
この問題だけで、
HashMapは辞書を保存した後、下付き0からすべての可能性を試して、1つを見つけて、下付きを結果セットに入れます.
public class Solution {
    public List<Integer> findSubstring(String S, String[] L) {
        List<Integer> res = new ArrayList<Integer>();
        if(S==null || S.length()==0 || L==null || L.length==0)
            return res;
        //HashMap          
        HashMap<String, Integer> dict = new HashMap<String, Integer>();
        for(String item : L){
            if(dict.containsKey(item))
                dict.put(item, dict.get(item)+1);
            else
                dict.put(item, 1);
        }
        int num = L.length;
        int len = L[0].length();
        for(int i=0; i<=S.length()-num*len; i++){
            HashMap<String, Integer> temp = new HashMap<String, Integer>(dict);
            int start = i;
            for(int j=0; j<num; j++){
                String sub = S.substring(start, start+len);
                if(temp.containsKey(sub)){
                    if(temp.get(sub)==1)
                        temp.remove(sub);
                    else
                        temp.put(sub, temp.get(sub)-1);
                }else
                    break;//  j  
                start = start + len;//      , start         
            }
            if(temp.size()==0)//            ,       i
                res.add(i);
        }
        return res;
    }
}