# 76. Minimum Window Substring

## 刷题内容

• 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);
}
};


apachecn/AiLearning