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开始尝试所有可能,找到一个,就把下标加入结果集。

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;
    }
}


你可能感兴趣的:(LeetCode,with,substring,Conca)