Substring with Concatenation of All Words

来源:互联网 发布:网络本科报名时间 编辑:程序博客网 时间:2024/06/05 00:16
class Solution {public:    vector<int> findSubstring(string s, vector<string>& words) {        int n = s.size();        int cnt = words.size();        vector<int> ans;        if(n<=0 || cnt<=0)            return ans;        unordered_map<string, int> dict;        for(int i=0; i<cnt; i++)        {            dict[words[i]]++;        }        int wl = words[0].size();        for(int i=0; i<wl; i++)        {            int left=i, count=0;            unordered_map<string, int> tdict;            for(int j=i; j<=n-wl; j+=wl)            {                string str = s.substr(j,wl);                if(dict.count(str))                {                    tdict[str]++;                    count++;                    while(tdict[str]>dict[str])                    {                        string tmp = s.substr(left, wl);                        tdict[tmp]--;                        count--;                        left += wl;                    }                    if(count==cnt)                    {                        ans.push_back(left);                    }                }                else                {                    tdict.clear();                    count = 0;                    left = j+wl;                }            }        }        return ans;    }};
0 0
原创粉丝点击