1. Use two pointers: start and end to represent a window.
2. Move end to find a valid window.
3. When a valid window is found, move start to find a smaller window.
Solution
public class Solution {
/**
* @param source: A string
* @param target: A string
* @return: A string denote the minimum window
* Return "" if there is no such a string
*/
public String minWindow(String source, String target) {
if (source == null || source.length() == 0 ||
target == null || target.length() == 0) {
return "";
}
int[] sourceHash = new int[256];
int[] targetHash = new int[256];
int ans = Integer.MAX_VALUE;
String minStr = "";
initTargetHash(targetHash, target);
int i = 0;
int j = 0;
for (i = 0; i < source.length(); i++) {
while (j < source.length() && !isValid(sourceHash, targetHash)) {
sourceHash[source.charAt(j)]++;
if (j < source.length()) {
j++;
} else {
break;
}
}
if (isValid(sourceHash, targetHash)) {
if (ans > j - i) {
ans = Math.min(ans, j - i);
minStr = source.substring(i, j);
}
}
sourceHash[source.charAt(i)]--;
}
return minStr;
}
boolean isValid(int[] sourceHash, int[] targetHash) {
for (int i = 0; i < sourceHash.length; i++) {
if (targetHash[i] > sourceHash[i]) {
return false;
}
}
return true;
}
public void initTargetHash(int[] targetHash, String target) {
for (int i = 0; i < target.length(); i++) {
targetHash[target.charAt(i)]++;
}
}
}