
滑动窗口
在 ss上滑动窗口,通过移动right指针不断扩张窗口。当窗口包含left全部所需的字符后,如果能收缩,我们就收缩窗口直到得到最小窗口。
 代码:
class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<char, int> hash_s, hash_t;
        for (auto ch : t)   hash_t[ch]++;
        string ans;
        int left = 0, right = 0, count = 0;
        while (right < s.size()) {
            hash_s[s[right]]++;
            if (hash_s[s[right]] <= hash_t[s[right]])
                count++;
            while ( hash_s[s[left]] > hash_t[s[left]]) {
                hash_s[s[left]]--;
                left++;
            }
            if (count == t.size()) {
                if ( ans.empty() || right - left + 1 < ans.size())
                    ans = s.substr(left, right - left + 1);
            }
            right++;
        }
        return ans;
    }
};
 
时间复杂度:O(n)
 空间复杂度:O(1)。










