Point to Offer II 014. Anagrams in string Point to Offer II 015. All anagrams in string

insert image description here
Ideas :
(1) Sliding window
    The core idea of ​​the sliding window here is to first intercept the first substring whose length is a short string in the long string, then move the right pointer to the right ++, and the left pointer to the right to –, which respectively represent joining A new number and reduce an old number, so that the substring can be found.

class Solution {
    
    
public:
    bool checkInclusion(string s1, string s2) {
    
    
        int n = s1.length(), m = s2.length();
        if (n > m) {
    
    
            return false;
        }
        vector<int> cnt1(26), cnt2(26);
        for (int i = 0; i < n; ++i) {
    
    
            ++cnt1[s1[i] - 'a'];
            ++cnt2[s2[i] - 'a'];
        }
        if (cnt1 == cnt2) {
    
    
            return true;
        }
        for (int i = n; i < m; ++i) {
    
    
            ++cnt2[s2[i] - 'a'];
            --cnt2[s2[i - n] - 'a'];
            if (cnt1 == cnt2) {
    
    
                return true;
            }
        }
        return false;
    }
};

insert image description here
Idea:
It is similar to the above idea. When you find a match, don’t return directly and use a vector to save it.

class Solution {
    
    
public:
    vector<int> findAnagrams(string s, string p) {
    
    
        int n = p.length(), m = s.length();
        vector<int>res;
        if (n > m) {
    
    
            return res;
        }
        vector<int> cnt1(26), cnt2(26);
        for (int i = 0; i < n; ++i) {
    
    
            ++cnt1[p[i] - 'a'];
            ++cnt2[s[i] - 'a'];
        }
        if (cnt1 == cnt2) {
    
    
            res.push_back(0);
        }
        for (int i = n; i < m; ++i) {
    
    
            ++cnt2[s[i] - 'a'];
            --cnt2[s[i - n] - 'a'];
            if (cnt1 == cnt2) {
    
    
                res.push_back(i-n+1);
            }
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/daweq/article/details/130205924