Minimum Window Substring | ||||||
| ||||||
Description | ||||||
Given a string S and a string T, find the minimum window in S which will contain all the characters. For example, S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC". Note: If there are multiple such windows, you are guaranteed the window with the shortest length and first appeared in the string S. | ||||||
Input | ||||||
There are multiple test cases, processing to the end-of-file. For each case: Line 1: This line contains string S. Line 2: This line contains string T. The string contains printable characters except space (visible characters). The length of the string is not less than 1 and not greater than 100,000. | ||||||
Output | ||||||
For each case: Output one line, contains the minimum window substring. If there is no such window in S that covers all characters in T, output the empty string "". | ||||||
Sample Input | ||||||
ADOBECODEBANC ABC acbdbaab aabd adobecodebancbbcaa abc 203838534736761996179497200837 746 ZHEXOMNHPRWMAJFPSUCYFZXUNLNRRU YUX dptpeaevzsykxnfurfbqcxdqkujgtc urn uLY7JdYK1810x95bT3LyPx7V37iLjY Jx8 w_J)u^^@gsWoXnTB*@CWAh./k9d3|% ^3w | ||||||
Sample Output | ||||||
BANC dbaa bca 4736 YFZXU nfur JdYK1810x w_J)u^^@gsWoXnTB*@CWAh./k9d3 |
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int Maxn = 100005;
char str1[Maxn];
char str2[Maxn];
int FirMap[260];
int SecMap[260];
int tempStart,tempEnd;
int Start,End;
int MinLength;
int main()
{
while(~scanf("%s",&str1))
{
scanf("%s",&str2);
memset(FirMap,0,sizeof(FirMap));
memset(SecMap,0,sizeof(SecMap));
int len_1 = strlen(str1);
int len_2 = strlen(str2);
for(int i=0;i<len_2;i++)
{
FirMap[str2[i]]++;
}
int ans = 0;
MinLength = len_1;
End = len_1;
Start = -1;
tempStart = 0;
int i;
for(int i=0;i<len_1;i++)
{
SecMap[str1[i]]++;
if(SecMap[str1[i]] <= FirMap[str1[i]])
{
ans++;
}
if(ans == len_2)
{
while(tempStart < i && SecMap[str1[tempStart]] > FirMap[str1[tempStart]])
{
SecMap[str1[tempStart]]--;
tempStart++;
}
if(i - tempStart < MinLength)
{
MinLength = i - tempStart;
End = i;
Start = tempStart;
}
SecMap[str1[tempStart]]--;
ans--;
tempStart++;
}
}
if(Start != -1)
for(int i=Start;i<=End;i++)
{
printf("%c",str1[i]);
}
printf("\n");
}
}