class Solution {
public static boolean compare(Map<Character, Integer> s, Map<Character, Integer> t) {
for (Character c : t.keySet()) {
if (s.getOrDefault(c, 0) < t.get(c))
return false;
}
return true;//表示比对成功
}
public static String minWindow(String s, String t) {
//设置left,right指针,left随着right的状态进行移动
//声明方法比较s的子串是否包含t,使用的是两个HashMap,所以该方法的参数为两个HashMap
//当窗口长度小于t长度的时候,right++,当窗口长度>=t字符串长度的时候开始进行比较
//当每次比对成功,记录下此时left和right的位置,然后left++再次尝试是否比对成功,若成功则替换原来的left位置,若不成功则righ++;如此循环往复,直至right=s.length()-1;
int min = Integer.MAX_VALUE;
int mleft = 0, mright = 0;
int left = 0, right = 0, n = s.length(), k = t.length();
if (n < k || s == null || t == null)
return "";
Map<Character, Integer> map_s = new HashMap<>();
Map<Character, Integer> map_t = new HashMap<>();
//给map_t赋值
for (Character c : t.toCharArray()) {
if (map_t.containsKey(c)) {
int count = map_t.get(c) + 1;
map_t.put(c, count);
} else {
map_t.put(c, 1);
}
}
//判断s中是否包含t的所有元素/、防止类似s="a",t="b";
for (char c : map_t.keySet()) {
if (s.indexOf(c) == -1)
return "";
}
while (right < n) {
int length = right - left + 1;
//给map_s赋值
if (map_s.containsKey(s.charAt(right))) {
int count = map_s.get(s.charAt(right)) + 1;
map_s.put(s.charAt(right), count);
} else {
map_s.put(s.charAt(right), 1);
}
if (length >= k) {
while (compare(map_s, map_t)) {
int current = right - left + 1;
if (min > current) {
mright = right;
mleft = left;
min = current;
}
int new_count = map_s.get(s.charAt(left)) - 1;
map_s.put(s.charAt(left), new_count);
left++;
}
}
right++;
}
if (min == Integer.MAX_VALUE)
return "";
return s.substring(mleft, mright + 1);
}
}
76. 最小覆盖子串
于 2025-07-27 14:19:25 首次发布