Problem:
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).
Example:
Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC"Note:
- If there is no such window in S that covers all characters in T, return the empty string
""
.- If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
Analysis:
本题的思路是维持一个HashMap,每次与T字符串进行匹配,看是否满足,然后找出长度最短的那个。代码如下:
Code:
class Solution {
public String minWindow(String s, String t) {
if(s.length() == 0 || t.length() == 0 || s.length() < t.length())
return "";
int minLen = s.length() + 1; // save minimum string length
int fir = -1, lat = -1;
int pre = 0, nxt = 0; // two pointer to traversal string
Map<Character, Integer> tChar = new HashMap<Character, Integer>(); // store string(t) character number
Map<Character, Integer> temp = new HashMap<Character, Integer>(); // cache every substring character number
for(int i = 0; i < t.length(); i++) {
char ch = t.charAt(i);
if(!tChar.containsKey(ch)) {
tChar.put(ch, 1);
} else {
tChar.put(ch, tChar.get(ch) + 1);
}
}
// traversal the string array
while(pre <= nxt && nxt < s.length()) {
char ch = s.charAt(nxt);
if(!temp.containsKey(ch)) {
temp.put(ch, 1);
} else {
temp.put(ch, temp.get(ch) + 1);
}
if(isWindow(tChar, temp)) {
while(pre <= nxt)
{
char pch = s.charAt(pre);
if(!tChar.containsKey(pch)) {
temp.remove(pch);
pre++;
} else if(tChar.get(pch) < temp.get(pch)) {
temp.put(pch, temp.get(pch) - 1);
pre++;
} else {
break;
}
}
if(minLen > nxt - pre + 1) {
minLen = nxt - pre + 1;
fir = pre;
lat = nxt;
}
}
nxt++;
}
// System.out.println(minLen + "=" + fir + ", " + lat);
return (minLen == s.length() + 1) ? "" : (fir == -1 ? "" :s.substring(fir, lat + 1));
}
public boolean isWindow(Map<Character, Integer> t, Map<Character, Integer> s) {
for(Map.Entry<Character, Integer> entry : t.entrySet()) {
Character keyStr = entry.getKey();
int val = entry.getValue();
if(!s.containsKey(keyStr) || s.get(keyStr) < val)
return false;
}
return true;
}
}