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.
Runtime: 5 ms beats 90.12% of java submissions.
public String minWindow(String s, String t) {
char[] ss = s.toCharArray(), tt = t.toCharArray();
int[] count = new int[128];
for (int i = 0; i < tt.length; i++) count[tt[i]]++;
int k = tt.length, minStart = 0, start = 0, minLen = Integer.MAX_VALUE;
for (int i = 0; i < ss.length; i++) {
if (count[ss[i]]-- > 0) k--;
while (k == 0) {
if (i - start + 1 < minLen) {
minLen = i - start + 1;
minStart = start;
}
count[ss[start]]++;
if (count[ss[start]] > 0) k++;
start++;
}
}
return minLen== Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen);
}
参考 https://discuss.leetcode.com/topic/30941/here-is-a-10-line-template-that-can-solve-most-substring-problems/12