[Algorithm Topic Breakthrough] Sliding Window - Concatenate substrings of all words (15)

Table of contents

1. Question analysis

2. Algorithm principle

3. Code writing

Write at the end:


1. Question analysis

Question link: 30. Concatenate substrings of all words - LeetCode

 This question is actually easy to understand. You can basically understand what it means by looking at the example.

The main thing is to find if there is a substring in s that we can splice, and then return the index.

2. Algorithm principle

We can treat the substrings in the substring array it gives as characters,

Treat each equal-length substring in the target substring s as a character,

We will find that this question is transformed into the question about anagrams we did before.

Let’s use the same idea to answer:

3. Code writing

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> ret;
        unordered_map<string, int> win;
        for(auto& e : words) win[e]++;

        int len = words[0].size(), m = words.size();
        for(int i = 0; i < len; i++) {
            unordered_map<string, int> hash;
            for(int left = i, right = i, count = 0; right + len <= s.size(); right += len) {
                string in = s.substr(right, len);
                hash[in]++;
                if(hash[in] <= win[in]) count++;
                if(right - left + 1 > len * m) {
                    string out = s.substr(left, len);
                    if(hash[out] <= win[out]) count--;
                    hash[out]--;
                    left += len;
                }
                if(count == m) ret.push_back(left);
            }
        }
        return ret;
    }
};

Write at the end:

That’s the content of this article, thank you for reading.

If you feel you have gained something, you can give the blogger a like .

If there are omissions or errors in the content of the article, please send a private message to the blogger or point it out in the comment area~

Guess you like

Origin blog.csdn.net/Locky136/article/details/131759224