76. 最小覆盖子串

 

我写了首诗,把滑动窗口算法变成了默写题 | labuladong 的算法小抄 (gitee.io)

//#define INF 0x3f3f3f3f;
class Solution {
public:
    string minWindow(string s, string t) {
        map windows;//窗口里的元素
        mapneed;//统计窗口中t中的字符
        for (int i = 0; i < t.size(); i++)
        {
            need[t[i]]++;
        }
        int left = 0;
        int right = 0;//滑动窗口,左闭右开
        int flag = 0;//标记窗口是否含有t中所有字符
        int len = INT_MAX;
        int start =0;
        char c;
        while (right < s.size())
        {
            c = s[right];
            right++;//right增加,往窗口里增加字符
            if (need.count(c))
            {
                windows[c]++;
                if (need[c] == windows[c])
                {
                    flag++;
                }
            }
            while (flag == need.size())
            {
                if (right - left < len)
                {
                    len = right - left;
                    start = left;
                }
                c = s[left];
                left++;
                if (need.count(c))
                {
                    if(windows[c]==need[c])
                    {
                        flag--;
                    }
                    windows[c]--;
                }
            }
        }
        if(len != INT_MAX)
        {
           return s.substr(start,len);
        }
        else
        {
           return "";
        }
    }
};

 

 

 

你可能感兴趣的:(滑动窗口,c++)