leetcode-Substring with Concatenation of All Words

来源:互联网 发布:淘宝卖家有发票吗 编辑:程序博客网 时间:2024/06/05 09:06

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" foobarman"
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) {        int n = L.size();        int m = L[0].length();        int k = S.length();        vector<int> ret;        if(k < m*n)return ret;        vector<int> a(k-m+1, -1);        map<string, int> strmap;        vector<int> c(n, 0);        for(int i = 0; i < n; i++)        {            map <string, int>::iterator iter;            iter = strmap.find(L[i]);            if(iter == strmap.end())            {                strmap[L[i]] = i;                c[i]++;            }            else             {                c[iter->second]++;            }        }        for(int i = 0; i < k-m+1; i++)        {            string s1 = S.substr(i, m);            map <string, int>::iterator iter;            iter = strmap.find(s1);            if(iter != strmap.end())a[i] = iter->second;        }        for(int i = 0; i < k-m+1; i++)                      {            vector<int> b(c);            int j = i;            int count = 0;            while((j < k-m+1)&&(count < n))            {                if(a[j] == -1)break;                else                {                    b[a[j]]--;                    j += m;                    count++;                }            }            for(int h = 0; h < n; h++)            {                if(b[h] != 0)break;                if(h == n-1)ret.push_back(i);            }        }        return ret;    }};


0 0
原创粉丝点击