您的位置:首页 > 其它

leetcode: Minimum Window Substring

2014-07-05 14:22 253 查看
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 emtpy string
""
.

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

两个指针,尾指针往后走,直到包含所有的T中字符,头指针再走,直到再走它和尾指针间就不包含所有T中字符为止,记录所有情况中最短的

class Solution {
public:
string minWindow(string S, string T) {
if( S.size() < T.size() || T.empty())
return "";
unordered_map< char, int> appear;
unordered_map< char, int> expect;
for( int i = 0; i < T.size(); ++i)
++expect[T[i]];
int length = INT_MAX, start = 0, appear_time = 0, min_start = 0;//最小窗口长度,起始位置,出现次数,最小窗口起始
for( int end = 0; end < S.size(); ++end){
if( expect[S[end]] > 0 ){
++appear[S[end]];
if( appear[S[end]] <= expect[S[end]] ){
++appear_time;
}
}
if( appear_time == T.size()){
while( appear[S[start]] > expect[S[start]] || expect[S[start]] == 0){
--appear[S[start]];
++start;
}
if( length > end -start + 1){
length = end - start + 1;
min_start = start;
}
}
}
if( length == INT_MAX)
return "";
return S.substr( min_start, length);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: