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).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".
  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.


    首先使用map,统计出T中每个字母的个数,然后设立左右两个指针,左指针指向S的头,右指针往右移动直至包含全部T的字母(每次遇到一个T中的字母,就将map中对应的元素减一,此处需要使用一个count记录已经匹配的字母数量,若map减一吼大于等于零,则count--,若map中元素小于零,说明已经匹配完成,现在的字母是多出来的,此时不需要再减count)。

    当count与T的长度相等时,说明包含了全部T的字母,此时将left指针往右移动,去掉多余的字母,计算最小长度。计算完后将left右移一位,重新变为未匹配完成状态,开始右移right指针进行匹配。

class Solution {
public:
    string minWindow(string s, string t) {
        int n1=s.size(), n2=t.size();
        string res="";
        int left=0,right=0,minlen=INT_MAX,count=0;
        if(n1 < n2)
            return res;
        unordered_map<char, int> m;
        for(char c : t)
            m[c]++;
        for(int i=0; i<n1; i++)
        {
            if(m.find(s[i])==m.end())
                continue;
            if(--m[s[i]]>=0)
                count++;
            if(count==n2)
            {
                while(m.find(s[left])==m.end() || ++m[s[left]]<=0)
                    left++;
                if(minlen > i-left+1)
                {
                    minlen=i-left+1;
                    res=s.substr(left,minlen);
                }
                count--;
                left++;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/jifeng7288/article/details/80267936