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 emtpy string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
思路:双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符后,然后再收缩头指针,直到不能再收缩为止,当找到一个之后,需要将头指针存储起来,从而下一次头指针还是从原来的头指针开始的。
public class Solution {
public String minWindow(String S, String T) {
if (S == null || S.length() == 0) {
return S;
}
if (T == null || T.length() == 0) {
return "";
}
HashMap<Character, Integer> tCounter = new HashMap<Character, Integer>();
Character c;
for (int i = 0; i < T.length(); i++) {
c = T.charAt(i);
if (tCounter.containsKey(c)) {
tCounter.put(c, tCounter.get(c) + 1);
} else {
tCounter.put(c, 1);
}
}
HashMap<Character, Integer> minWindowCounter = new HashMap<Character, Integer>();
String minWindow = null;
int tCount = T.length();
int begin = 0, end = 0,temp=0;
for (end = 0; end < S.length(); end++) {
c = S.charAt(end);
if (!tCounter.containsKey(c)) {
continue;
}
if(minWindowCounter.containsKey(c)){
minWindowCounter.put(c, minWindowCounter.get(c) +1);
}else {
minWindowCounter.put(c, 1);
}
if (minWindowCounter.get(c) <=tCounter.get(c)) {
tCount--;
}
if (tCount == 0) {
for (begin = temp; begin <= end; begin++) {
c = S.charAt(begin);
if (!tCounter.containsKey(c)) {
continue;
}
if (minWindowCounter.get(c) <=tCounter.get(c)) {//头指针不能再收缩了
temp=begin;
if(minWindow==null||end+1-begin<minWindow.length()){
minWindow = S.substring(begin, end + 1);
}
break;
}else{
minWindowCounter.put(c, minWindowCounter.get(c)-1);
}
}
}
}
return minWindow!=null?minWindow:"";
}
}