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.
基本解题思路:
sliding window: start from a window that is tight.
Try moving the start forward and then see if it is possible to tighten the window.
public class Solution {
public String minWindow(String S, String T) {
// solve this problem by sliding window
int tlen = T.length(), slen = S.length();
int[] cnt = count(T);
int[] covered = new int[256];
int min_len = slen+1, start = 0;
String ans = "";
int cover = 0;
for(int i=0; i<slen; i++){
char ch = S.charAt(i);
if(cnt[ch] > 0){
if(covered[ch] < cnt[ch]) cover++;
covered[ch] ++;
}
if(cover == tlen){
// can be the end of the minimum substring
while(start < i){
char chs = S.charAt(start);
if(cnt[chs] > 0 && cnt[chs] == covered[chs]) break;
else if(cnt[chs] > 0){ covered[chs]--; }
start++;
}
int len = i-start+1;
if(len < min_len){
min_len = len;
ans = S.substring(start, i+1);
}
}
}
return ans;
}
private int[] count(String str){
int[] cnt = new int[256];
int len = str.length();
for(int i=0; i<len; i++){
char ch = str.charAt(i);
cnt[ch] ++;
}
return cnt;
}
}
Space Complexity: O(1) though the count array/hashmap could take 256, but it is still constant
Time complexity: O(max(S.len, T.len)), need to scan T once and scan S twice.