【发布时间】:2012-06-02 21:33:36
【问题描述】:
给定一个字符串 S 和一个字符串 T,找到 S 中包含 T 中所有字符的最小窗口,复杂度为 O(n)。
例如,
S = "ADOBECODEBANC"
T = "ABC"
最小窗口是"BANC"。
void getstring(char str1[],char str2[],char hash[])
{
int len=strlen(str1);
int i=0,j; //i keeps the previous index
int min=INT_MAX;
int cnt=0;
for(j=0;j<len;j++)
{
if(hash[str1[j]]==-1) //means uninitialized, will be checked for first time only
{
cnt++;
hash[str1[j]]=j;
if(cnt==1)
i=j;
int y=check(hash,str2); //checking for the characters
//printf("y=%d",y);
if(y) //means all the characters are present
{
if( (j-i+1)<min)
{
min=j-i+1;
I=i;
J=j;
}
}
}
else if(hash[str1[j]]>=0)
{
hash[str1[j]]=j;
if(check(hash,str2) )
{
if( hash[str1[i]]==hash[str1[j]] ) //it means that we are moving the first
{ //index only
i=getmin(hash,str2); //get minimum index of the element
if( (j-i+1)<min)
{
min=j-i+1;
I=i;
J=j;
}
}
//else
}
else
{
if( hash[str1[i]]==hash[str1[j]] )
i=hash[str1[i]];
}
}//end of else-if
}//end of for
}
我已经使用哈希为其编写了代码,即我将字符串 T 的字符的索引值保留在哈希中并使用两个索引,只要我得到任何与较低索引处的字符相同的字符,我先检查长度,然后更新索引。
这种方法在最坏的情况下需要 O(nk)。
n - is the number of characters in S
k - is the number of characters in T
是否有任何方法会花费O(n) 时间来解决这个问题?
【问题讨论】:
-
您能否包含所有代码,包括
getmin()和check()并正确格式化您的代码? -
实际上它没有为所有测试用例提供正确的输出,所以我没有包含整个代码。