76. Minimum Window Substring
Sliding Window
class Solution {
public String minWindow(String s, String t) {
int[] memo = new int[128];
for(int i = 0; i < t.length(); i++){
memo[t.charAt(i)]++;
}
int count = t.length(), left = 0, right = 0;
int p1=0, p2=Integer.MAX_VALUE;
while(right<s.length()){
// first check if the char at right is in t
// then check if count == 0
// (means the window contians all characters in t)
if(memo[s.charAt(right++)]-- >0) count--;
while(count == 0){
if(right-left<p2-p1) {
// left is inclusive
p1=left;
// right is exclusive because of right++
p2=right;
}
if (memo[s.charAt(left++)]++==0) count++;
}
}
return p2==Integer.MAX_VALUE ? "" : s.substring(p1, p2);
}
}
Last updated
Was this helpful?