You are given a string s
, a string t
. Returns the smallest substring s
covering t
all characters in . Returns an empty string if no substring s
covering all characters exists in .t
""
Notice:
- For
t
repeated characters, the number of characters in the substring we are looking for must be no less than thet
number of characters in the substring. - If
s
such a substring exists in , we guarantee that it is the only answer.
Idea 1: Sliding window
char * minWindow(char * s, char * t){
int hash[58] = {0};
int lenS = strlen(s);
int lenT = strlen(t);
int min = 0, max = INT_MAX;
for (int i = 0; i < lenT; ++i) hash[t[i] - 'A']++;
for (int j = 0, i = 0; j < lenS; ++j) {
if (hash[s[j] - 'A'] > 0) lenT--;
hash[s[j] - 'A']--;
while (lenT == 0) {
if (j - i + 1 < max - min + 1) {
max = j;
min = i;
}
if (++hash[s[i] - 'A'] > 0) lenT++;
i++;
}
}
if (max == INT_MAX) return "";
char* res = malloc(sizeof(char) * (max - min + 2));
int i = 0;
while (min <= max) res[i++] = s[min++];
res[i] = '\0';
return res;
}
Time complexity O(n^2), space complexity O(n)
analyze:
First establish a hash table, store the number of each English letter in the hash table, subtract one from the corresponding position of the hash table according to the character of s[i], and constantly judge whether it is the smallest substring, and finally output the substring covering t
Summarize:
This question examines the application of sliding windows, and it can be solved by clearly writing the judgment of whether it is the smallest substring