题目:
题解:
char* minWindow(char* s, char* t) {
int tLen = strlen(t);
int hash[256] = { 0 };
for (int i = 0; i < tLen; ++i)
++hash[t[i]];
for (int i = 0; i < 256; ++i) {
if (0 == hash[i])
hash[i] = INT_MIN;
}
int left, right, count, start, minLen, sLen;
left = right = count = 0;
start = -1;
minLen = INT_MAX;
sLen = strlen(s);
for (right; right < sLen; ++right) {
if (hash[s[right]] > INT_MIN) {
if (hash[s[right]] > 0)
++count;
--hash[s[right]];
}
if (count == tLen) {
while (hash[s[left]] < 0) {
if (hash[s[left]] > INT_MIN)
++hash[s[left]];
++left;
}
if (right - left + 1 < minLen) {
minLen = right - left + 1;
start = left;
}
++hash[s[left]];
++left;
--count; //注意只丢弃第一个字符
}
}
if (start == -1) {
char* ans = (char*)malloc(sizeof(char));
if (ans) {
*ans = '\0';
return ans;
}
}
else {
char* ans = (char*)malloc(sizeof(char) * minLen + 1);
if (ans) {
int i = 0, j = start;
for (i; i < minLen; ++i) {
ans[i] = s[j];
++j;
}
ans[minLen] = '\0';
return ans;
}
}
return NULL;
}