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"
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
和很多字符串包含的题思路一样,都是维护S字符串的一个窗口,窗口右边一直往后移动,直到窗口内包含所有T中字符串停止,此时窗口左边开始移动,直到窗口刚好不满足包含T中所有字符串则停止,计算更新最小串。
public class Solution {
public String minWindow(String S, String T) {
if (S == null || T == null) {
return "";
}
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < T.length(); i++) {
char curChar = T.charAt(i);
if (map.containsKey(curChar)) {
map.put(curChar, map.get(curChar) + 1);
} else {
map.put(curChar, 1);
}
}
String res = "";
int minLen = S.length() + 1;
int pre = 0;
int count = 0;
int len = T.length();
for (int i = 0; i < S.length(); i++) {
char curChar = S.charAt(i);
if (map.containsKey(curChar)) {
map.put(curChar, map.get(curChar) - 1);
if (map.get(curChar) >= 0) {
count++;
}
while (count == len) {
if (map.containsKey(S.charAt(pre))) {
map.put(S.charAt(pre), map.get(S.charAt(pre)) + 1);
if (map.get(S.charAt(pre)) > 0) {
count--;
}
if (i - pre + 1 < minLen) {
res = S.substring(pre, i + 1);
minLen = i - pre + 1;
}
}
pre++;
}
}
}
return res;
}
}