LeetCode 76. Minimum Window Substring

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example,

S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC".

Note:

If there is no such window in S that covers all characters in T, return the empty string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

标准的尺取法

class Solution
{
public:
    string minWindow(string s, string t)
    {
        unordered_map<char, int> mp, mk;
        int x = 0;
        for(auto &i : t)
        {
            if(mp[i] == 0)
                x ++;
            mp[i] ++;
        }
        int y = 0, mininum = s.size()+1;
        string ans;
        for(int b = 0, e = 0; ;)
        {
            while(e<s.size())
            {
                ++ mk[s[e]];
                if(mk[s[e]] == mp[s[e]])
                    y ++;
                e ++;
                if(y == x)
                    break;
            }
            if(y == x)
            {
                while(b < e)
                {
                    if(mk[s[b]] == mp[s[b]])
                        y --;
                    -- mk[s[b]], ++ b;
                    if(y < x)
                        break;
                }
                if(e - b + 1 < mininum)
                {
                    mininum = e - b + 1;
                    ans = s.substr(b-1, e-b+1);
                }
            }
            if(e >= s.size())
                break;
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/aiterator/p/6710787.html