您的位置:首页 > 其它

[LeetCode]Minimum Window Substring

2014-01-14 22:19 393 查看
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).

For example,
S =
"ADOBECODEBANC"

T =
"ABC"


Minimum window is
"BANC"
.

Note:
If there is no such window in S that covers all characters in T, return the emtpy string
""
.

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

思考:虽然也想到了时间换空间的方法,但是时间复杂度还是不能压到O(n)。我的思路是二维数组记录T中每个字符的index,然后转化为一个求最短距离。

参考:http://discuss.leetcode.com/questions/97/minimum-window-substring

此方法的精妙之处在于count!

class Solution {
public:
string minWindow(string S, string T) {
int p1[256]={0}; //need to find
int p2[256]={0}; //has found
int count=0;
int len1=S.size();
int len2=T.size();
for(int i=0;i<len2;i++) p1[T[i]]++;
int start=0,end=0;
int len=INT_MAX; //window大小
int pos=-1;
for(;end<len1;end++)
{
if(p1[S[end]]==0) continue; //S[end]不在T中,跳过
p2[S[end]]++;
if(p2[S[end]]<=p1[S[end]]) count++;
if(count==len2) //找到一个window
{
while(p1[S[start]]==0||p2[S[start]]>p1[S[start]])
{
if(p2[S[start]]>p1[S[start]]) p2[S[start]]--;
start++;
}
if(len>end-start+1)
{
len=end-start+1;
pos=start;
}
}
}
return (pos==-1)?"":S.substr(pos,len);
}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: