给定两个字符串 sp,找到 s 中所有 p异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。

    异位词 指由相同字母重排列形成的字符串(包括相同的字符串)。

    示例 1:

    1. 输入: s = "cbaebabacd", p = "abc"
    2. 输出: [0,6]
    3. 解释:
    4. 起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。
    5. 起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。

    示例 2:

    输入: s = "abab", p = "ab"
    输出: [0,1,2]
    解释:
    起始索引等于 0 的子串是 "ab", 它是 "ab" 的异位词。
    起始索引等于 1 的子串是 "ba", 它是 "ab" 的异位词。
    起始索引等于 2 的子串是 "ab", 它是 "ab" 的异位词。
    

    提示:

    • 1 <= s.length, p.length <= 3 * 10^4
    • sp 仅包含小写字母
    //这题看长度范围,10^4,说明不能用n平方的时间复杂度,这样做会超时
    class Solution {
    public:
        vector<int> findAnagrams(string s, string p) {
            int slen = s.size(), plen = p.size();
            if(slen<plen) return {};
            string sp=p;
            sort(sp.begin(),sp.end());
            vector<int>ans;
            for (int i = 0; i <= slen-plen; i++)
            {
                string tem=s.substr(i,plen);
                sort(tem.begin(),tem.end());
                if(tem==sp)ans.push_back(i); 
            }
            return ans;
        }
    };
    
    class Solution {
    public:
        vector<int> findAnagrams(string s, string p) {
            int sLen = s.size(), pLen = p.size();
            if (sLen < pLen) return vector<int>();
            vector<int> ans;
            vector<int> sCount(26);
            vector<int> pCount(26);
            //第一个位置行不行
            for (int i = 0; i < pLen; ++i) {
                ++sCount[s[i] - 'a'];
                ++pCount[p[i] - 'a'];
            }
            if (sCount == pCount) ans.push_back(0);
            //从i开始,滑动窗口,减去前面一个,加上后面一个
            for (int i = 0; i < sLen - pLen; ++i) {
                --sCount[s[i] - 'a'];
                ++sCount[s[i + pLen] - 'a'];
                if (sCount == pCount) ans.push_back(i + 1);
    
            }
    
            return ans;
        }
    };