和乙個目標字串target
,在字串source
中找到包括所有目標字串字母的子串。
如果在source
中沒有這樣的子串,返回"",如果有多個這樣的子串,返回起始位置最小的子串。
——不需要。 ,
target =
"abc"
滿足要求的解
"banc"
演算法流程如下:
1. 先將target中所有的字元出現的次數儲存到td陣列中。
2. 遍歷source陣列,開始時start=0,i=0;
start記錄當前字串的起點,i相當於當前字串的終點。
用found表示當前字串中包含target中字元的數目,如果found=target.length()則表明當前字串包含了target中所有字元,如果滿足,進入下一步。
3. 將start後移,取出start前面多餘的元素,已達到字串最小的目標。
4.判斷,如果當前字串小於歷史搜到的最小字串,則將當前字串的長度,起始點,結束點都記錄,更新。
5.將start後移,尋找下乙個字串。
public static string minwindow(string source , string target)
if(target==null || target.length()==0)
int td = new int[256];
for (char tc:target.tochararray())
int sd = new int[256];
int minlen = source.length();
int start = 0;
int first = -1, end = 0;
int found = 0; // 在source中發現了target中元素的數目
for (int i = 0; i < source.length(); i++)
if(found==target.length())
// 處理2:如果比當前最小子串小,則更新
if(i+1-start<=minlen)
sd[source.charat(start)]--;
start++;
found--;}}
if(first==-1)else
}
最小子串覆蓋 LintCode
給定乙個字串source和乙個目標字串target,在字串source中找到包括所有目標字串字母的子串。注意事項 如果在source中沒有這樣的子串,返回 如果有多個這樣的子串,返回起始位置最小的子串。說明 在答案的子串中的字母在目標字串中是否需要具有相同的順序?不需要。樣例 給出source ad...
32 最小子串覆蓋
中文english 給定兩個字串source和target.求source中最短的包含target中每乙個字元的子串.樣例 1 輸入 source abc target ac 輸出 abc 樣例 2 輸入 source adobecodebanc target abc 輸出 banc 解釋 banc...
最小子串覆蓋
給定乙個字串source和乙個目標字串target,在字串source 中找到包括所有目標字串字母的子串。注意事項 如果在source 中沒有這樣的子串,返回 如果有多個這樣的子串,返回起始位置最小的子串。您在真實的面試中是否遇到過這個題?yes 說明在答案的子串中的字母在目標字串中是否需要具有相同...