Leetcode|滑动窗口|567. 字符串的排列

2021-09-22 11:23:19 浏览数 (1)

1 滑动窗口

代码语言:javascript复制
class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        unordered_map<char, int> need, window;
        for (auto& c : s1) need[c]  ;
        int left = 0, right = 0, vaild = 0;
        int len = s1.size();
        while (right < s2.size()) {
            char in = s2[right];
            right  ;
            if (need.count(in)) {
                window[in]  ;
                if (window[in] == need[in]) vaild  ;
            }
            while (vaild == need.size()) {
                // 基于滑动窗口模板上的修改
                if (right - left == len) return true;
                char out = s2[left];
                left  ;
                if (window.count(out)) {
                    if (window[out] == need[out]) vaild--;
                    window[out]--;
                }
            }
        }
        return false;
    }
};

0 人点赞