Leetcode热题100-438 找出字符串中所有字母异位数-3. 代码实现

时间:2024-09-30 15:22:11
class Solution {
public:
    // 定长滑动窗口,窗口的大小为字符串p的长度
    vector<int> findAnagrams(string s, string p) {
        // 用以保存最终结果
        vector<int> res;
        unordered_map<char, int> need, window;
        for (auto ch : p) {
            need[ch]++;
        }
        int left = 0, right = 0;

        while (right < s.size()) {
            char c = s[right++];
            if (need.count(c)) {
                window[c]++;
            }
            // 恰好等于窗口的大小时,判断该窗口是否合理
            if (right - left == p.size()) {
                if (window == need) {
                    res.push_back(left);
                }
                char d = s[left++];
                if (need.count(d)) {
                    window[d]--;
                }
            }
        }
        return res;
    }
};