Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 30. Substring with Concatenation of All Words

Rain Hu
class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        unordered_map<string, int> cnt1, cnt2;
        for (const auto& word : words) cnt1[word]++;
        int wordLen = words[0].size();
        int k = words.size();
        vector<int> res;
        if (s.size() < wordLen * k) return res;
        for (int start = 0; start < wordLen; start++) {
            cnt2.clear();
            int valid = 0;
            for (int i = start; i < k * wordLen; i += wordLen) {
                string sin = s.substr(i, wordLen);
                if (cnt1.count(sin) && ++cnt2[sin] == cnt1[sin]) valid++;
            }
            if (valid == cnt1.size()) res.push_back(start);
            for (int i = start + k * wordLen; i < s.size(); i += wordLen) {
                string sin = s.substr(i, wordLen);
                if (cnt1.count(sin) && ++cnt2[sin] == cnt1[sin]) valid++;
                string sout = s.substr(i-k*wordLen, wordLen);
                if (cnt1.count(sout) && cnt2[sout]-- == cnt1[sout]) valid--;
                if (valid == cnt1.size()) res.push_back(i-(k-1)*wordLen);
            }
        }
        return res;
    }
};

Share this post on:

Previous
[LeetCode] 15. 3Sum
Next
[LeetCode] 438. Find All Anagrams in a String