您的位置:首页 > 其它

[LeetCode]Minimum Window Substring

2015-11-26 20:13 239 查看



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);
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: