Minimum Window Substring--LeetCode

来源:互联网 发布:会员数据分析维度 编辑:程序博客网 时间:2024/06/07 19:15

1.题目

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.

2.题意

找出s中能包含t的最小窗口

3.分析

遍历t,在m中记录t中各个字符出现的次数
遍历s,更改s中各个字符在m中出现的次数
当子串包含t时,尝试将左边界右移,从而缩小窗口

注意判断left与right时不要写反
还有while循环里面++left一定不要遗漏

4.代码

class Solution {public:    string minWindow(string s, string t) {        string result;        if(s.size() < t.size())            return result;        unordered_map<char, int> m;        for(int i = 0; i < t.size(); ++i)        {            if(m.find(t[i]) != m.end())                ++m[t[i]];            else                m[t[i]] = 1;        }        int left = 0;        int count = 0;        int minLen = s.size() + 1;        for (int right = 0; right < s.size(); ++right)        {            if(m.find(s[right]) != m.end())            {                --m[s[right]];                if(m[s[right]] >= 0)                    ++count;                while(count == t.size())                {                    if(right - left + 1 < minLen)                    {                        minLen = right - left + 1;                        result = s.substr(left, minLen);                    }                    if(m.find(s[left]) != m.end())                    {                        ++m[s[left]];                        if(m[s[left]] > 0)                            --count;                    }                    ++left;                }            }        }        return result;    }};