1龙考、t[256] 記錄 target字符串每個(gè)字符出現(xiàn)的次數(shù)箱硕;
2、int start, i;
i首先遍歷source唐础,遍歷到從 start 到 i 的子串包含 target ;是否包含根據(jù)兩個(gè)數(shù)組間的值來(lái)判斷找到的字符數(shù)量箱歧,來(lái)判斷是否包含。
然后從start開(kāi)始遍歷一膨,去除無(wú)用的字符呀邢。
用變量begin、end保存當(dāng)前start 到 i的字符串豹绪。
start后移一位驼鹅,此時(shí)一定不滿(mǎn)足包含條件,再后移 i 找到新的符合條件的字符串森篷。
參考:https://blog.csdn.net/u012156116/article/details/80648698
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 *t = new int[256]();
for(int i = 0;i < target.length();i++){
t[target[i]]++;
}
int *s = new int[256]();
int found = 0; //找到的字符數(shù)量
int start = 0;
int begin = 1,end = 0;
int len = source.length()+1;
for(int i = 0;i < source.length();i++){
s[source[i]]++;
if(s[source[i]] <= t[source[i]]) //target中沒(méi)有的為0,存在的話(huà)豺型,source取到一次就加1仲智。
{
found++;
}
if(found == target.length()){
while(start < i && s[source[start]] > t[source[start]]){
s[source[start]]--;
start++;
} //去除前面多余的字符
if(i-start+1 < len){
begin = start;
end = i;
len = i - start + 1;
}
start++; //將start后移 尋找其他子串
found--; //后移后 肯定不再滿(mǎn)足條件
}
}
if(begin > end){
return ""; //對(duì)應(yīng)一個(gè)子串也沒(méi)找到的情況
}
string res = source.substr(begin,end-begin+1);
return res;
}
};