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 empty string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
思路:同向指针,主指针i,辅指针j移动,注意C的阈值的加一减一,只有C超过target里面的count数目的时候,C才进行加减;
另外,j = ss.length的时候,还要继续等i进行移动,因为是找最短的substring,后面可能还有C == K的时候,依然满足情况的更小的substring。
class Solution {
public String minWindow(String s, String t) {
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
int[] tcount = new int[256];
int[] scount = new int[256];
int K = 0;
for(int i = 0; i < t.length(); i++) {
if(tcount[tt[i]] == 0) {
K++;
}
tcount[tt[i]]++;
}
int j = 0;
int start = 0; int end = 0;
int len = Integer.MAX_VALUE;
int C = 0;
for(int i = 0; i < s.length(); i++) {
// move j;
while(j < s.length() && C < K) {
scount[ss[j]]++;
if(scount[ss[j]] == tcount[ss[j]]) {
C++;
}
j++;
}
// update res;
if(C == K) {
if(j - i < len) {
len = j - i;
start = i;
end = j;
}
}
// move i;
scount[ss[i]]--;
if(scount[ss[i]] < tcount[ss[i]]) {
C--;
}
}
return s.substring(start, end);
}
}