Wednesday, July 2, 2014

Leetcode - 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].
[Thoughts]: create两个hash map, 一个装L里的string 和 count作为对比组,另外一个用于循环验证
public class Solution {
    public List<Integer> findSubstring(String S, String[] L) {
        List<Integer> res = new ArrayList<Integer>();
        if(L.length==0) return res;
        
        HashMap<String, Integer> expectMap = new HashMap<String, Integer>();
        HashMap<String, Integer> realMap = new HashMap<String, Integer>();
        //初始化两个map,expectMap是L中string和count,用于对比
        for(String str:L){
            if(expectMap.containsKey(str))
                expectMap.put(str, expectMap.get(str)+1);
            else{
                expectMap.put(str, 1);
                realMap.put(str, 0);
            }
        }
        
         int len = L[0].length();//L中string的长度相同,都为len
         //i从0到S.length()-L.length*len
         for(int i=0; i<=S.length()-L.length*len; i++){
             int j = 0;
             for(; j<L.length; j++){
                 String sub = S.substring(i+j*len, i+j*len+len);
                 if(expectMap.containsKey(sub))
                    realMap.put(sub, realMap.get(sub)+1);
                 else
                    break;
                if(realMap.get(sub) > expectMap.get(sub)) 
                    break;
             }
             
             if(j==L.length)//若if条件满足,说明从i开始的位置匹配成功
                res.add(i);
             for(Map.Entry<String, Integer> entry : realMap.entrySet())
                realMap.put(entry.getKey(),0);
         }
        
        return res;
    }
}

No comments:

Post a Comment