【中等】找到字符串中所有字母异位词

【中等】找到字符串中所有字母异位词_第1张图片

class Solution {
private:
    unordered_map<char, int> need, window;
public:
    vector<int> findAnagrams(string s, string p) {
        for (char c : p) need[c]++;
        int left = 0, right = 0, valid = 0;
        int start = 0, len = INT_MAX;
        vector<int> ans;
        while (right < s.size())
        {
            char c = s[right++];
            if (need.count(c))
            {
                window[c]++;
                if (window[c] == need[c])
                    valid++;
            }
            while (valid == need.size())
            {
                len = right - left;
                if (len == p.size())
                    ans.push_back(left);
                char d = s[left++];
                if (need.count(d))
                {
                    if (window[d] == need[d])
                        valid--;
                    window[d]--;
                }
            }
        }
        return ans;
    }
};

你可能感兴趣的:(#,滑动窗口,leetcode,算法,职场和发展)