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) 
    {        
        vector< int> ret;
         int lsize=L.size();
         if(lsize== 0return ret;

         int slen=S.length();
         int wordlen=L[ 0].length();
        
        map< string, int> lmap;
         for( int i= 0;i<lsize;i++)
             if(lmap.find(L[i])==lmap.end())
                lmap[L[i]]= 1;
             else
                lmap[L[i]]++;

         for( int i= 0;i<slen-lsize*wordlen+ 1;i++)
        {        
            map< string, int> imap;
             bool valid= true;
             for( int j= 0;j<lsize;j++)
            {
                 int start=i+j*wordlen;
                 string word=S.substr(start,wordlen);
                imap[word]++;
                 if(lmap.find(word)==lmap.end() || lmap[word]<imap[word])
                {
                    valid= false;
                     break;
                }
                
            }
             if(!valid)  continue;
             else
                ret.push_back(i);
        }
         return ret;
    }
};  

你可能感兴趣的:(substring)