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;
    }
};
posted @ 2020-06-20 16:05  景云ⁿ  阅读(60)  评论(0编辑  收藏  举报