76. Minimum Window Substring
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public String minWindow(String s, String t) {
if(s == null || t == null || s.isEmpty()) return "";
int sLen = s.length(), tLen = t.length();
int[] sHash = new int[128];
int[] tHash = new int[128];
char[] sChars = s.toCharArray();
char[] tChars = t.toCharArray();
for(char ch: tChars) {
tHash[ch]++;
}
int left = 0, start = -1, count = 0, minLen = Integer.MAX_VALUE;
for(int right = 0; right < sLen; right++) {
char ch = sChars[right];
sHash[ch]++;
if(tHash[ch] != 0 && sHash[ch] <= tHash[ch]) count++;
if(count == tLen) {
while(tHash[sChars[left]] == 0 ||
sHash[sChars[left]] > tHash[sChars[left]]) {
if(sHash[sChars[left]] > tHash[sChars[left]]) {
sHash[sChars[left]]--;
}
left++;
}
if(minLen > right-left+1) {
minLen = right-left+1;
start = left;
}
}
}
return (start == -1)? "": s.substring(start, start+minLen);
}
}