Notes:
The basic idea is counting and comparing with a sliding window or two-pointer method.
One detail is how to compare? If we compare the counting arrays or hash table directly, it will be costly. One better way is we just need a counting variable to count the total number of valid letters.
See the code below:
class Solution {
public:
string minWindow(string s, string t) {
int len1 = s.size(), len2 = t.size();
if(len1 < len2) return "";
int start = 0, len = 0;
vector v1(256, 0), v2(256, 0);
for(auto &a : t) ++v2[a];
int i = 0, j = 0, ct = 0;
while(i < len1 && j < len1) {
++v1[s[j]];//move right pointer
if(v1[s[j]] <= v2[s[j]]) ++ct;//only count when the letter is valid;
if(ct == len2) {
while(i < j && v2[s[i]] < v1[s[i]]) --v1[s[i++]];//move left pointer
if(len == 0 || len > j - i + 1) {
len = j - i + 1;
start = i;
}
}
++j;
}
return s.substr(start, len);
}
};
No comments:
Post a Comment