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.
解题思路:首先要知道T字符串中各个字符的个数。然后遍历s串,记录在满足包含T串中所有字符的前提下字符串左端的最右边的位置,然后求取当前情况下得到长度值,取所有这些长度的最小值并存储条件符合的字符串的起始点和终止点。总的时间复杂度为O(128n),即O(n),常数有点大。。。。
class Solution {
public:
string minWindow(string s, string t) {
vector<int> count[130];
int cnt[130];
for(int i = 0; i < 130; ++i) {
cnt[i] = 0;
}
int ans = 0x3f3f3f3f;
int sp, ep;
int tlen = t.length();
int slen = s.length();
char ch = (t[0] >= 'a' && t[0] <= 'z' ? 'a' : 'A');
int size;
string ret = "";
for(int i = 0; i < tlen; ++i) {
cnt[(int)t[i]]++;
}
for(int i = 0; i < slen; ++i) {
count[(int)s[i]].push_back(i);
int t = 0x3f3f3f3f, tt;
for(int j = 0; j < 128; ++j) {
if(cnt[j] > 0) {
size = count[j].size();
if(size >= cnt[j]) {
tt = count[j][size-cnt[j]];
} else {
tt = -0x3f3f3f3f;
}
t = min(t, tt);
if(t < 0) break;
}
}
if(ans > i-t+1) {
ans = i-t+1;
sp = t;
ep = i;
}
}
if(ans >= 0x3f3f3f3f) return ret;
for(int i = sp; i <= ep; ++i) {
ret += s[i];
}
return ret;
}
};