Thursday, April 10, 2014

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).
Solution:
Simple implementation, use map to store the number of occurance, to consider two or more happening case.
Code:
vector findSubstring(string S, vector &L) {
      vector res;
        int num = L.size();
        int len = L[0].size();
        if (num==0){return res;}
        map mp;
        for (int i=0;i
        int i=0;
        while ((i+num*len-1)            map mp2;
            int j=0;
            while (j                string subs = S.substr(i+j*len,len);
                if (mp.find(subs)==mp.end()){
                        break;
                }else{
                    mp2[subs]++;
                    if (mp2[subs]>mp[subs]){
                        break;
                    }
                    j++;
                }
            }
            if (j==num){res.push_back(i);}
            i++;
        }

        return res;
}

No comments:

Post a Comment