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.
方法一:暴力搜索 从最小长度开始找出能包含所有t元素的结果:
public String minWindow(String s, String t) {
if (s == null || s.isEmpty() || t == null || t.isEmpty() || t.length() > s.length()) {
return "";
}
// 滑窗的个数
int slideNum = t.length();
while (slideNum <= s.length()) {
int begin = 0;
while (begin <= s.length() - slideNum) {
Map<Character, Integer> testMap = new HashMap<>();
for (int i = begin; i < begin+slideNum; i++) {
testMap.put(s.charAt(i), testMap.getOrDefault(s.charAt(i), 0)+1);
}
boolean conti = true;
for (int i = 0; i < t.length(); i++) {
Integer res = testMap.get(t.charAt(i));
if (res == null) {
conti = false;
break;
}else {
if(res<=1) {
testMap.remove(t.charAt(i));
}else {
testMap.put(t.charAt(i), res-1);
}
}
}
if (conti) {
return s.substring(begin, begin+slideNum);
}
begin++;
}
slideNum++;
}
return "";
}
超时,方法优化。
方法二:
1.我们从两个指针开始,left和right最初指向字符串S的第一个元素。
2.我们使用right指针展开窗口,直到我们得到一个理想的窗口,即包含T的所有字符的窗口。
3.一旦我们有一个包含所有字符的窗口,我们就可以将左指针一个接一个地向前移动。 如果窗口仍然是理想的窗口,我们继续更新最小窗口大小。
4.如果窗口不再需要,我们重复步骤步骤2。
public String minWindow(String s, String t) {
if (s == null || s.isEmpty() || t == null || t.isEmpty() || t.length()>s.length()) {
return "";
}
//存储所有的t字符的数据
Map<Character,Integer> tDicMap = new HashMap<>();
for(int i=0;i<t.length();i++) {
tDicMap.put(t.charAt(i),tDicMap.getOrDefault(t.charAt(i), 0)+1);
}
//所需要的所有t中不同元素的总长度
int required = tDicMap.size();
//s中的窗口数据中已经拥有了的长度
int format = 0;
int l = 0,r=0;
// 分别代表长度 开始 结尾
int[] ans = {-1, 0, 0};
//包含的所有 元素map
Map<Character,Integer> windowsMap = new HashMap<>();
while(r<s.length()) {
char c= s.charAt(r);
windowsMap.put(c, windowsMap.getOrDefault(c, 0)+1);
if(tDicMap.containsKey(c) && tDicMap.get(c).intValue()==windowsMap.get(c).intValue()) {
format++;
}
while(l<=r && format==required) {
c=s.charAt(l);
if(ans[0] == -1 || r-l+1 < ans[0]) {
ans[0] =r-l+1;
ans[1] = l;
ans[2] = r;
}
windowsMap.put(c, windowsMap.get(c)-1);
if(tDicMap.containsKey(c) && windowsMap.get(c) < tDicMap.get(c)) {
format--;
}
l++;
}
r++;
}
return ans[0]==-1?"":s.substring(ans[1],ans[2]+1);
}
这里调用两个Map和两个int来表示 是否两个字符串之间s1和s2之间 s1包含了s2的所有字符