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).


class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) {
    
        map<string, int> LMap;
        
        vector<int> retVtr;
        int wordLen = L[0].size();
        int windowSize = wordLen * L.size();
        
        if (S.size() < windowSize)
            return retVtr;
            
        for (int i=0; i<L.size(); i++)
            LMap[L[i]]++;
        
        int windowIdx = 0;
        while (windowIdx <= S.size()-windowSize)
        {
            map<string, int> curMap;
            int wordIdx = 0;
            for (; wordIdx <L.size(); wordIdx++)
            {
                int curIdx = windowIdx + wordIdx*wordLen;
                string tmp = S.substr(curIdx, wordLen);
                
                if (LMap.find(tmp) == LMap.end()) 
                {  
                    windowIdx++;
                    break;
                }
                
                curMap[tmp]++;
                if (curMap[tmp] > LMap[tmp])
                {
                    windowIdx++;
                    break;
                }
            }
            
            if (wordIdx == L.size())
            {
                retVtr.push_back(windowIdx);
                windowIdx += wordLen;
            }
        }
        
        return retVtr;
    }
};


你可能感兴趣的:(Substring with Concatenation of All Words)