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.
题目主要思路是使用两个指针移动来进行判断是否满足条件,从而得到结果。第二种思路在某些方面有所优化,但感觉实际效果不佳。(上面为第二种解法,下面为第一种解法。)
解法一:
public String minWindow(String s, String t) {
if(s.length() == 0 || t.length() == 0) return "";
//字符串t中不重复字符个数
Map<Character, Integer> tc = new HashMap<>();
for(int i = 0; i < t.length(); ++i) {
tc.put(t.charAt(i), tc.getOrDefault(t.charAt(i), 0) + 1);
}
int tnum = tc.size();
//返回结果,依次表示最短字符串长度和其左右边界
int[] ans = new int[]{-1, 0, 0};
//要移动的两个指针和移动过程中已经匹配的不重复字符个数
int l = 0, r = 0, matched = 0;
//移动l,r过程中不重复字符串个数
Map<Character, Integer> sc = new HashMap<>();
//开始移动l和r指针
while(r < s.length()) {
char c = s.charAt(r);
sc.put(c, sc.getOrDefault(c, 0) + 1);
//某个不重复字符个数已达到则已匹配字符个数加一
if(tc.containsKey(c) && tc.get(c).intValue() == sc.get(c).intValue()) {
++matched;
}
//开始移动l指针
while(l < r && matched == tnum) {
if(ans[0] == -1 || ans[2] - ans[1] + 1 < ans[0]){
ans[0] = ans[2] - ans[1] + 1;
ans[1] = l;
ans[2] = r;
}
c = s.charAt(l);
sc.put(c, sc.get(c) - 1);
if(tc.containsKey(c) && sc.get(c).intValue() < tc.get(c).intValue()) {
--matched;
}
++l;
}
++r;
}
return ans[0] == -1 ? "" : s.substring(ans[1], ans[2] + 1);
}
解法二:
public String minWindow(String s, String t) {
if(s.length() == 0 || t.length() == 0) return "";
//字符串t中不重复字符个数
Map<Character, Integer> tc = new HashMap<>();
for(int i = 0; i < t.length(); ++i) {
tc.put(t.charAt(i), tc.getOrDefault(t.charAt(i), 0) + 1);
}
int tnum = tc.size();
//返回结果,依次表示最短字符串长度和其左右边界
int[] ans = new int[]{-1, 0, 0};
//要移动的两个指针和移动过程中已经匹配的不重复字符个数
int l = 0, r = 0, matched = 0;
//移动l,r过程中不重复字符串个数
Map<Character, Integer> sc = new HashMap<>();
//提取s中只存在于t中的字符
List<Pair<Character, Integer>> ns = new ArrayList<>();
for(int i = 0; i < s.length(); ++i) {
if(tc.containsKey(s.charAt(i))) {
ns.add(new Pair<>(s.charAt(i), i));
}
}
//开始移动l和r指针
while(r < ns.size()) {
Pair<Character, Integer> rpair = ns.get(r);
char c = rpair.getKey();
sc.put(c, sc.getOrDefault(c, 0) + 1);
//某个不重复字符个数已达到则已匹配字符个数加一
if(tc.containsKey(c) && tc.get(c).intValue() == sc.get(c).intValue()) {
++matched;
}
//开始移动l指针
while(l <= r && matched == tnum) {
Pair<Character, Integer> lpair = ns.get(l);
if(ans[0] == -1 || rpair.getValue() - lpair.getValue() + 1 < ans[0]){
ans[0] = rpair.getValue() - lpair.getValue() + 1;
ans[1] = lpair.getValue();
ans[2] = rpair.getValue();
}
c = lpair.getKey();
sc.put(c, sc.get(c) - 1);
if(tc.containsKey(c) && sc.get(c).intValue() < tc.get(c).intValue()) {
--matched;
}
++l;
}
++r;
}
return ans[0] == -1 ? "" : s.substring(ans[1], ans[2] + 1);
}