给定一个字符串source和一个目标字符串target,在字符串source中找到包括所有目标字符串字母的子串。
样例
给出source = "ADOBECODEBANC",target = "ABC" 满足要求的解 "BANC"
注意
如果在source中没有这样的子串,返回"",如果有多个这样的子串,返回起始位置最小的子串。
挑战
说明
要求时间复杂度为O(n)
在答案的子串中的字母在目标字符串中是否需要具有相同的顺序?
——不需要。
class Solution {
public:
/**
* @param source: A string
* @param target: A string
* @return: A string denote the minimum window
* Return "" if there is no such a string
*/
string minWindow(string &source, string &target) {
// write your code here
int sourceCount[256];
memset(sourceCount, 0, sizeof(sourceCount));
int targetCount[256];
memset(targetCount, 0, sizeof(targetCount));
int m = source.length();
int n = target.length();
for (int i = 0; i < n; i++)
{
targetCount[target[i]]++;
}
int begin = -1;
int count = 0;
int minLen = INT_MAX;
int minBegin = -1;
for (int i = 0; i < m; i++)
{
if (targetCount[source[i]] > 0)
{
sourceCount[source[i]]++;
if (sourceCount[source[i]] <= targetCount[source[i]])
{
count++;
if (begin == -1)
{
begin = i;
}
if (count == n)
{
minBegin = begin;
minLen = i - begin + 1;
}
}
else
{
if (source[begin] == source[i])
{
while (targetCount[source[begin]] < 1
|| sourceCount[source[begin]] > targetCount[source[begin]])
{
if (sourceCount[source[begin]] > targetCount[source[begin]])
{
sourceCount[source[begin]]--;
}
begin++;
}
if (count == n)
{
int temp = i - begin + 1;
if (temp < minLen)
{
minBegin = begin;
minLen = temp;
}
}
}
}
}
}
if (minBegin != -1)
{
return source.substr(minBegin, minLen);
}
return "";
}
};