您的位置:首页 > 其它

LeetCode--Minimum Window Substring

2017-10-11 10:44 375 查看
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.

思路:哈希表法。这里用两个数组tm和sm代替哈希表,首先统计T中每个字母的个数(可能一个字母有多个),然后开始滑动窗口,左端点起点为0,遍历右端点,如果遇到S中有T中的字母且个数不超过T中该字母的个数,则计数加1,直到计数达到T中字母个数,即S中窗口包含T为止,如果该窗口小于最小窗口长度,则更新最小窗口,同时左端点前移,如果左端点包含T中字母,则减去一个S中该字母的个数,若此时所需T中该字母个数不够,则计数减1,继续前移右窗口,滑动窗口直到结束。

class Solution {
public:
string minWindow(string S, string T) {
if (T.size()>S.size()) return "";
string res="";
int left=0,count=0,minLen=S.size()+1;
int tm[256]={0},sm[256]={0};
for(int i=0;i<T.size();i++) tm[T[i]]++;
for(int right=0;right<S.size();right++){
if(tm[S[right]]){
sm[S[right]]++;
if(sm[S[right]]<=tm[S[right]]) count++;
while(count==T.size()){
if(right-left+1<minLen){
minLen=right-left+1;
res=S.substr(left,minLen);
}
if(tm[S[left]]){
sm[S[left]]--;
if(sm[S[left]]<tm[S[left]]) count--;
}
left++;
}
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: