Leetcode 76 Minimum Window Substring
Approach 1: Sliding Window
Algorithm:
-
We start with two pointers, left and right initially pointing to the first element of the string S. 双指针,left 和 right。
-
We use the rightright pointer to expand the window until we get a desirable window i.e. a window that contains all of the characters of T. 移动right指针, 直到包含所有T的字符。
-
Once we have a window with all the characters, we can move the left pointer ahead one by one. If the window is still a desirable one we keep on updating the minimum window size. 当window有所有的字符之后,移动left指针,如果window仍然包含所有字符,继续移动left。
-
If the window is not desirable any more, we repeat step 2. 移动做指针之后不包含所有字符,则移动right。
class Solution {
public String minWindow(String s, String t) {
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
if (tt.length == 0) {
return "";
}
int T = 0;
int[] cntT = new int[256];
int[] cntS = new int[256];
for(char c: tt){
++cntT[c];
if(cntT[c] == 1){
++T;
}
}
int ansl =-1;
int ansr = -1;
int l=0;
int r=0;
int now = 0;
for(l=0; l<s.length(); ++l){
while(r<s.length() && now<T){
++cntS[ss[r]];
// ss[r] may be repeat in String t.
if(cntS[ss[r]] == cntT[ss[r]]){
++now;
}
++r;
}
if (now == T) {
if (ansl == -1 || r - l < ansr - ansl) {
ansl = l;
ansr = r;
}
}
-- cntS[ss[l]];
//ss[r] may be repeat in String t.
if(cntS[ss[l]] ==cntT[ss[l]] - 1){
--now;
}
}
if (ansl == -1) {
// r > s.length && now <T
return "";
}else{
return s.substring(ansl, ansr);
}
}
}
For example:
Input: S = “ADOBECODEBANC”, T = “ABC”
Output: “BANC”
- left = 0 right = 5
- left =1 right = 10
- left = 2 right = 10
- left =3 right =10
- left = 4 right =10
- …
- left = 9 right = 12
Input: S = “ABBBBAABBANC”, T = “AAC”
Output: “ABBANC”
cntT[‘A’] = 2 cntT[‘C’] =1 and T=2
we need find a windows which satisfy cntS[‘A’] = 2 cntS[‘C’] =1 and now=2