leetcode-----30. 串联所有单词的子串

代码

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> ans;
        if (words.empty()) return ans;
        int n = s.size(), m = words.size(), w= words[0].size();

        unordered_map<string, int> map;
        for (auto word: words) map[word]++;

        for (int i = 0; i < w; ++i) {
            unordered_map<string, int> wd;
            int cnt = 0;
            for (int j = i; j + w <= n; j += w) {
                if (j >= i + m * w) {
                    auto word = s.substr(j - m * w, w);
                    wd[word]--;
                    if (wd[word] < map[word]) cnt--;
                }
                auto word = s.substr(j, w);
                wd[word]++;
                if (wd[word] <= map[word]) cnt++;
                if (cnt == m) ans.push_back(j - (m - 1) * w);
            }
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/clown9804/p/13169048.html