Substring with Concatenation of All Words

来源:互联网 发布:ubuntu tensorflow 编辑:程序博客网 时间:2024/06/05 15:31
-----QUESTION-----

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

class Solution {public:    vector<int> findSubstring(string S, vector<string> &L) {        string word;        int wordLen = L[0].length();        int counter = 0;        vector<int> result;        map<string,int> mapL;        map<string,int> mapS;        map<string,int>::iterator itMap;        for(int i = 0; i < L.size(); i++)          {            ++mapL[L.at(i)];         }            int last = S.length()-wordLen * L.size()+1;        for(int i = 0; i< last; i++)        {            word = S.substr(i,wordLen);            itMap = mapL.find(word);            while(itMap!= mapL.end())             {                ++mapS[word];                 if(mapS[word]>mapL[word]) break;                counter+=1;                if(counter == L.size())                {                    result.push_back(i);                    break;                }                word = S.substr(i+counter*wordLen,wordLen);                itMap = mapL.find(word);            }            counter = 0;            mapS.clear();        }        return result;    }};

0 0
原创粉丝点击