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.
题目求字符串S中包含字符串T的最小窗口。
使用滑动窗口的方式求解。代码如下:
char* minWindow(char* s, char* t) {
int windowsCharTotal[256] = {0};
int tCharTotal[256] = {0};
int needCharTypes = 0;
char* minWindowStart = s;
int tl = 0;
char *p = t;
while(*p != '\0'){
if(tCharTotal[*p] == 0){
++needCharTypes;
}
++tCharTotal[*p];
++p;
}
tl = p - t;//t 的长度,显然最优解长度不会低于这个值
p = s;
int minWindowsL = 0;
while(*s !='\0'){
char c = *s;
++s;
++windowsCharTotal[c];
if(windowsCharTotal[c] == tCharTotal[c]){
--needCharTypes;
}
if(needCharTypes == 0){//满足需求
while(true){//移动窗口开始的位置得到最当前优解
char lc = *p;
--windowsCharTotal[lc];
if(windowsCharTotal[lc] == tCharTotal[lc] -1){//如果窗口左侧再移动下窗口就失效了。所以这是局部最优解
if(minWindowsL == 0 //还没有遇到过
|| s - p < minWindowsL){
minWindowsL = s - p;
minWindowStart = p;
if(minWindowsL == tl){//已经是最短的了
minWindowStart[minWindowsL] = '\0';
return minWindowStart;
}
}
++p;
++needCharTypes;
break;
}
++p;
}
}
}
minWindowStart[minWindowsL] = '\0';//复用s
return minWindowStart;
}