您的位置:首页 > 其它

LeetCode : Minimum Window Substring

2012-12-04 15:26 357 查看
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.

这道题做的好辛苦,改来改去改了半天,要是面试的时候遇上就挂了。回头得再仔细看看。

class Solution {
public:
string minWindow(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int m = S.size();
int n = T.size();
int count = 0;
int total = 0;
int max = m+1;
int idx = 0;
int begin = 0;
int end = 0;
string res;
int map[256];
memset(map, 0, sizeof(map));
int q_map[256] = {0};
for(int i = 0 ;i< n; ++i){
map[T[i]]++;
}
while(end < m){
char c = S[end];
if(map[c]){
q_map[c]++;
if(q_map[c] <= map[c])
count++;

if(count == n){
while((begin < m && map[S[begin]] == 0) || q_map[S[begin]] > map[S[begin]]){
if(q_map[S[begin]]){
--q_map[S[begin]];
}
++begin;
}
int len = end - begin + 1;
if(len < max){
max = len;
idx = begin;
}
}
else{
if(q_map[S[begin]] > map[S[begin]]){
q_map[S[begin]]--;
begin++;
}
}
}
++end;
}
return (max <= m) ? S.substr(idx, max): "";
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: