您的位置:首页 > 其它

leetcode- Minimum Window Substring

2014-09-25 16:43 417 查看
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.

class Solution {
public:
string minWindow(string S, string T) {
int n = S.size();
if(n == 0) return "";
int m = T.size();
if(m == 0) return "";
int num;
vector<int> a(52,0);
vector<bool> b(52,false);
int count = 0;
for(int i = 0; i < m; i++)
{
if(T[i] - 'a' >= 0)
{
num = T[i] - 'a';
}
else num = T[i] - 'A'+26;
if(a[num] == 0)
{
a[num] = 1;
count++;
b[num] = true;
}
else a[num]++;
}

int ret1 = 0, ret2 = n;
int l = 0, r = 0;
int c = 0;
bool exsit = false;
while(l < n)
{
if(c < count && r < n)
{
if(S[r] - 'a' >= 0)
{
num = S[r] - 'a';
}
else num = S[r] - 'A'+26;
r++;

if(!b[num])continue;

a[num]--;
if(a[num] == 0)
{
c++;
if(c == count)
{
if(r-l <= ret2-ret1)
{
ret1 = l;
ret2 = r;
exsit = true;
}
}
}
}
else
{
if(S[l] - 'a' >= 0)
{
num = S[l] - 'a';
}
else num = S[l] - 'A'+26;
l++;
if(b[num])
{
a[num]++;
if(a[num] > 0)
{
c--;
}
}

if(c == count && r-l < ret2-ret1)
{
ret1 = l;
ret2 = r;
}
}

}
if(!exsit) return "";
return S.substr(ret1, ret2-ret1);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: