Skip to content

76. Minimum Window Substring

难度:Hard

刷题内容

原题连接

  • https://leetcode.com/problems/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.

˼· **- ʱ¼ä¸´ÔÓ¶È: O(N)*- ¿Õ¼ä¸´ÔÓ¶È: O(N)***

¸Õ¿ªÊ¼Ïëµ½Óà map È¥×ö£¬µ«ÊÇÕâµÀÌâµÄ¼üÖµÊÇ×Ö·û£¬Òò´Ë¿ÉÒÔÓÃÊý×éÈ¥×ö£¬ÕâÑùʱ¼ä¸´ÔÓ¶ÈΪO(n)¡£ÏëÓÃÒ»¸öÊý×éÿ¸ö×Ö·û³öÏֵĴÎÊý¡£½Ó×űéÀú s¡£¹Ì¶¨Ò»¸öÇø¼ä£¬Ê¹ÔÚÕâ¸öÇø¼äÄÚµÄ×Ó×Ö·û´®°üº¬×Ö·û´® t£¬Í¬ÑùÒ²¿ÉÒÔÓÃÒ»¸öÊý×é´¢´æÕâ¸öÇø¼ä¡£½Ó×ÅÏòÓÒÒƶ¯Çø¼ä¼´¿É¡£ÕÒµ½×î¶ÌµÄÇø¼ä¡£

class Solution {
public:
    string minWindow(string s, string t) {
        int arr[128],alNum = t.length();
        memset(arr,0,sizeof(arr));
        for(int i = 0;i < t.length();++i)
            arr[t[i]]++;
        vector<int> v;
        for(int i = 0;i < s.length();++i)
            if(arr[s[i]])
                v.push_back(i);
        int s_map[128],beg = -1,en,ans = INT_MAX,count1 = 0,l,r;
        memset(s_map,0,sizeof(s_map));
        for(int i = 0;i < v.size();++i)
        {
            if(count1 != alNum)
            {
                if(beg == -1)
                    beg = i;
                s_map[s[v[i]]]++;
                if(s_map[s[v[i]]] <= arr[s[v[i]]])
                    count1++;
            }
            for(int j = beg;count1 == alNum;)
            {
                en = v[i];
                s_map[s[v[j]]]--;
                if(ans > en - v[beg])
                {
                    l = v[beg];
                    r = en;
                    ans = en - v[beg];
                }
                if(s_map[s[v[j]]] < arr[s[v[j]]])
                    count1--;
                beg = ++j;
            }
       }
        if(ans == INT_MAX)
            return "";
        return s.substr(l,r - l + 1);
    }
};


回到顶部