您的位置:首页 > 其它

LeetCode OJ 之 Minimum Window Substring (最小窗口子串)

2015-02-04 09:45 525 查看

题目:

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.
给定字符串S和T,在S中找出最小的窗口包含T中所有的字符。时间复杂度为O(n)。
注意:

如果找不到包含T中所有的字符,返回空串。

如果有多个这样的窗口,确保返回唯一的最小窗口。

思路:

双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有T 的字符后,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的.

代码:

class Solution {
public:
string minWindow(string S, string T)
{
if(S.empty() || S.size() < T.size())
return "";
int appeared_count[256] = {0};
int expected_count[256] = {0};//数组记录T中相应字符出现的次数,比如字符串"aabb",expected_count[97] = 2,expected_count[98] = 2,类似于哈希表,键表示字符,值表示字符出现的次数
for(int i = 0 ; i < T.size() ; i++)
expected_count[T[i]]++;
int minWidth = INT_MAX , min_start = 0;//minWidth记录最小窗口的长度,min_start记录最小窗口的起始位置
int wnd_start = 0;//当前窗口的起始位置
int appeared = 0;//appeared记录S中出现的T中的字符的个数,当appeared==T.size()时,说明找到一个符合条件的
for(int wnd_end = 0 ; wnd_end < S.size() ; wnd_end++)
{
if(expected_count[S[wnd_end]] > 0)
{
appeared_count[S[wnd_end]]++;
if(appeared_count[S[wnd_end]] <= expected_count[S[wnd_end]])
appeared++; //当字符S[wnd_end]出现的次数不大于T中出现次数时,appeared才++
}
if(appeared == T.size())
{
while(appeared_count[S[wnd_start]] > expected_count[S[wnd_start]] ||
expected_count[S[wnd_start]] == 0)
{
appeared_count[S[wnd_start]]--;
wnd_start++;
}
if(minWidth > (wnd_end - wnd_start + 1))
{
minWidth = wnd_end - wnd_start + 1;
min_start = wnd_start;
}
}
}
if(minWidth == INT_MAX)
return "";
else
return S.substr(min_start , minWidth);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: