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 empty string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
要求查找S中包含T中所有字母的最短子串
解题思路:
建立两个索引表,分别用来存储T中每个字母出现的次数(即needfound)和已经查找过的在start到end中间的各字母的出现次数
class Solution {
public:
string minWindow(string s, string t) {
vector<int> found(128,0);
vector<int> tt(128,0);
for(int i=0;i<t.length();i++)
tt[t[i]]++;
found[s[0]]++;
int count=t.length(),start=0,end=0,ans=s.length()+1,minbegin=0;
if(tt[s[0]]>=found[s[0]])
count--;
while(end<s.length()){
if(count==0){
while(found[s[start]]>tt[s[start]]){
found[s[start]]--;
start++;
}
if(end-start+1<ans){
ans=end-start+1;
minbegin=start;
}
}
end++;
found[s[end]]++;
if(tt[s[end]]>=found[s[end]])
count--;
}
if(ans>s.length())
return "";
return s.substr(minbegin,ans);
}
};