刚开始的代码是这样的,发现在测试用例 bba ab 下输出是b。原因是在
if (map.containsKey(s[right])) {
map.put(s[right], map.get(s[right]) - 1);
match--;
}
这里,right到第二个b的时候,发现b也是包含在map中的,match也无脑减1了。match等于0,其实这里的match等于0不能表示left到right全部包含了T中的字符了。
import java.util.HashMap;
public class Solution {
public String minWindow(String S, String T) {
char[] s = S.toCharArray();
char[] t = T.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < t.length; i++) {
if (map.containsKey(t[i])) {
map.put(t[i], map.get(t[i]) +1);
} else {
map.put(t[i], 1);
}
}
int left = 0, right = 0, match = t.length, min = Integer.MAX_VALUE;
String res = "";
while (right < s.length) {
if (map.containsKey(s[right])) {
map.put(s[right], map.get(s[right]) - 1);
match--;
}
if (match <= 0) {
while (left < s.length) {
if (!map.containsKey(s[left]) || map.get(s[left]) < 0) {
if (map.containsKey(s[left]) && map.get(s[left]) < 0) {
map.put(s[left], map.get(s[left]) + 1);
match++;
}
left++;
} else {
break;
}
}
if (min > right - left +1) {
min = right - left + 1;
res = S.substring(left, right +1);
}
}
right++;
}
return res;
}
}
提交还有一个错误
if (map.containsKey(s[left]) && map.get(s[left]) < 0) {
map.put(s[left], map.get(s[left]) + 1);
match++;
}
这里match++是不需要的,在T中字符不欠,尚且多余的时候,match始终是0。
正确结果如下。
【点评】这道题的思路是通过map先遍历一遍字符串T,获得相应信息。从而实现复杂度是O(N)
public class Solution {
public static void main(String[] args) {
System.out.println(minWindow("ADOBECODEBANC","ABC"));
System.out.println(minWindow("bba","ab"));
}
public static String minWindow(String S, String T) {
char[] s = S.toCharArray();
char[] t = T.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < t.length; i++) {
if (map.containsKey(t[i])) {
map.put(t[i], map.get(t[i]) +1);
} else {
map.put(t[i], 1);
}
}
int left = 0, right = 0, match = t.length, min = Integer.MAX_VALUE;
String res = "";
while (right < s.length) {
if (map.containsKey(s[right])) {
if (map.get(s[right]) > 0) {
match--;
}
map.put(s[right], map.get(s[right]) - 1);
}
if (match == 0) {
while (left < s.length) {
if (!map.containsKey(s[left]) || map.get(s[left]) < 0) {
if (map.containsKey(s[left]) && map.get(s[left]) < 0) {
map.put(s[left], map.get(s[left]) + 1);
}
left++;
} else {
break;
}
}
if (min > right - left +1) {
min = right - left + 1;
res = S.substring(left, right +1);
}
}
right++;
}
return res;
}
}