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所有字符的最小窗口(类似于文本摘要提取)
用两个指针:start、end
1)若未包含所有字符,则end++;
2)若包含所有字符,则start++,直到不包含为止,得到窗口大小并与当前最小窗口比较并更新。
public class Solution {
public String minWindow(String S, String T) {
int min = S.length()+1;
int minStart = 0;
boolean flag = false;
int count=T.length();
int[] count1 = new int[256];
Map<Character, Boolean> map = new HashMap<Character, Boolean>();
int start=0,end=0;
for(int i=0;i<T.length();i++){
count1[T.charAt(i)]++;
map.put(T.charAt(i), true);
}
for(end=0;end<S.length();end++){
if(map.containsKey(S.charAt(end))&&map.get(S.charAt(end))){
count1[S.charAt(end)]--;
if(count1[S.charAt(end)]>=0){
count--;
}
}
if(count==0){
while(count==0){
if(map.containsKey(S.charAt(start))&&map.get(S.charAt(start))){
count1[S.charAt(start)]++;
if(count1[S.charAt(start)]>0)
count++;
}
start++;
}
if(end-start+2<min){
min=end-start+2;
minStart=start-1;
}
}
}
if(min==S.length()+1)
return "";
return S.substring(minStart,minStart+min);
}
}
最小覆盖子串算法
本文介绍了一种在字符串S中寻找包含字符串T所有字符的最小子串的方法,并提供了一个复杂度为O(n)的解决方案。该算法使用双指针技术(start和end),通过不断移动end指针来尝试覆盖T的所有字符,一旦覆盖则开始移动start指针以缩小窗口,直至找到最短的有效子串。
665

被折叠的 条评论
为什么被折叠?



