leetcode Substring with Concatenation of All Words

来源:互联网 发布:视频教学软件 编辑:程序博客网 时间:2024/06/05 09:52
class Solution {public:    vector<int> findSubstring(string s, vector<string>& words) {        for(const auto word : words)            mp[word]++;        int length = words[0].size();        for (int i = 0; i < length; ++i){ // 开始的匹配位置            for (int j = i; j + length<= s.size();j += length){                string cmp = s.substr(j, length);                auto iter = mp.find(cmp);                if (iter == mp.end())                    clearQueue(s, length);// 出现不匹配                else{                    iter->second--;// 需要匹配的tmp 次数减一                    que.push(j);                    if (iter->second < 0){      /* 说明 cmp 多匹配了一次,需要从queue从头开始删除,直到删除完第一个cmp   被删除的每个元素str对应的mp[str]自增 */                        string tmp;                        do{                            int pos = que.front();                            tmp = s.substr(pos, length);                            mp[tmp]++;                            que.pop();                        }while(tmp != cmp);                    }                    if (que.size() == words.size())                        ret.push_back(que.front());                }            }            clearQueue(s, length);        }        return ret;    }private:    unordered_map<string, int> mp;    vector<int> ret;    queue<int> que;    void clearQueue(string& s , const int length){        while(!que.empty()){            int pos = que.front();            string tmp = s.substr(pos, length);            mp[tmp]++;            que.pop();        }    }};


                                             
0 0
原创粉丝点击