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.
双指针,用hash来维护匹配的字符。然后伸缩前指针,注意收缩的原则。如果出现新的数字可以替代现在的前面数字就收缩解集。
class Solution {
public:
string minWindow(string s, string t) {
int min = INT_MAX;
int subs = 0;
vector<int> appearedNum(300,0);
vector<int> expectNum(300,0);
for(int i=0; i<t.length(); ++i){
expectNum[t[i]]++;
}
int start=0,end = 0;//初始化
int count = 0;
for(end=0; end<s.length(); ++end){
if(expectNum[s[end]]>0){
appearedNum[s[end]]++;
if(appearedNum[s[end]]<=expectNum[s[end]])
count++;
}//统计出现数字
if(count == t.length()){//出现可收缩解的情况就收缩头指针
while(appearedNum[s[start]]>expectNum[s[start]]||expectNum[s[start]]==0){
appearedNum[s[start]]--;
start++;
}
if(min>end-start+1){
min = end-start+1;
subs = start;
}
}
}
if(count<t.length()) return "";
else return s.substr(subs,min);
}
};
本文介绍了一种在字符串S中寻找包含字符串T所有字符的最短子串的算法,复杂度为O(n)。通过使用双指针技术和哈希表维护匹配字符的状态,实现了高效的子串查找。
770

被折叠的 条评论
为什么被折叠?



