1、t[256] 記錄 target字符串每個(gè)字符出現(xiàn)的次數(shù);
2、int start, i;
i首先遍歷source,遍歷到從 start 到 i 的子串包含 target ;是否包含根據(jù)兩個(gè)數(shù)組間的值來判斷找到的字符數(shù)量,來判斷是否包含。
然后從start開始遍歷,去除無用的字符。
用變量begin、end保存當(dāng)前start 到 i的字符串。
start后移一位,此時(shí)一定不滿足包含條件,再后移 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中沒有的為0,存在的話,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--; //后移后 肯定不再滿足條件
}
}
if(begin > end){
return ""; //對應(yīng)一個(gè)子串也沒找到的情況
}
string res = source.substr(begin,end-begin+1);
return res;
}
};