您的位置:首页 > 编程语言 > C语言/C++

[leetcode] Minimum Window Substring

2014-07-04 16:42 447 查看
tips:

count统计需要满足的各个string数目

found统计到目前为止已经包含的各个string数目

num统计满足count内的found数目(超出时不统计)

begin和end去维护满足条件的窗口首尾

保证满足条件的情况下更新begin和end,当begin位置的字符串found数目大于count时可后移,否则后移end直到begin可移动

代码如下:

class Solution {
public:
string minWindow(string S, string T) {
unordered_map<char, int> count;
unordered_map<char, int> found;
int index = 0, minLen = INT_MAX;
int num = 0;
for(int i = 0; i < T.length(); ++i)
count[T[i]] ++;
int begin = 0, end = 0;
while(begin < S.length() && count[S[begin]] == NULL)
begin++;
for(int i = begin; i < S.length(); ++i)
{
if(count[S[i]] != NULL)
{
found[S[i]]++;
if(found[S[i]] <= count[S[i]])
num++;
if(num == T.length())
{
end = i;
if(end - begin + 1 < minLen)
{
minLen = end - begin + 1;
index = begin;
}
break;
}
}
}
if(num != T.length())
return "";
while(end < S.length())
{
while(found[S[begin]] > count[S[begin]])
{
found[S[begin]]--;
begin++;
while(begin < S.length() && count[S[begin]] == NULL)
begin++;
if(end - begin + 1 < minLen)
{
minLen = end - begin + 1;
index = begin;
}
}
end++;
while(end < S.length() && count[S[end]] == NULL)
end++;
if(end < S.length())
found[S[end]]++;
}
if(minLen == INT_MAX)
return "";
return S.substr(index, minLen);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode c++