package _191103_滑动窗口;
import java.util.*;
/*
给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串。
示例:
输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"
说明:
如果 S 中不存这样的子串,则返回空字符串 ""。
如果 S 中存在这样的子串,我们保证它是唯一的答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-window-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class _76最小覆盖子串 {
public static void main(String[] args) {
}
private static String minWindow(String s, String t) {
if (s.length() == 0 || t.length() == 0) {
return "";
}
//tMap记录字符串t中每个字符出现的次数
Map<Character, Integer> tMap = new HashMap<Character, Integer>();
// 使用HashMap存入次数的方法1111111111111111111111111111111111111
// for (int i = 0; i < t.length(); i++) {
// char tChar = t.charAt(i);
// if (tMap.containsKey(tChar)) {
// tMap.put(tChar, tMap.get(tChar) + 1);
// } else {
// tMap.put(tChar, 1);
// }
// }
// 使用HashMap存入次数的方法222222222222222222222222222222222222
for (int i = 0; i < t.length(); i++) {
int num = tMap.getOrDefault(t.charAt(i), 0);
tMap.put(t.charAt(i), num + 1);
}
//记录tMap中字符的个数(去重后)
int tMapSize = tMap.size();
//左右指针
int left = 0;
int right = 0;
//记录窗口中的满足条件的字符个数(去重后)
int count = 0;
//创建滑动窗口对象
Map<Character, Integer> window = new HashMap<Character, Integer>();
//自定义数组,当当前窗口满足覆盖条件时,记录当前子串的长度,以及左右索引位置
int[] result = {-1, 0, 0};
//当右指针超过字符串长度时,循环结束
while (right < s.length()) {
//获取右指针指向s的字符,并保存当前字符以及当前字符出现的次数在window中
char sRightChar = s.charAt(right);
//记录次数的方式同上
int num = window.getOrDefault(sRightChar, 0);
window.put(sRightChar, num + 1);
//Integer引用数据类型使用==进行值的比较出现的问题
//判断当前字符是否存在以t中,如果存在并且当前字符出现在window中的次数与在tMap出现的次数相同,则count++
if (tMap.containsKey(sRightChar) && window.get(sRightChar).intValue() == tMap.get(sRightChar).intValue()) {
count++;
}
//当count == tMapSize时,说明当前window满足条件
while (left <= right && count == tMapSize) {
//保存当前子串数据到result中
if (result[0] == -1 || right - left + 1 < result[0]) {
result[0] = right - left + 1;
result[1] = left;
result[2] = right;
}
//获取左指针指向s的字符
char sLeftChar = s.charAt(left);
//改变左指针指向s的字符在window中的个数
window.put(sLeftChar, window.get(sLeftChar) - 1);
//如果左指针指向s的字符存在tMap中,并且左指针指向s的字符在window中出现的次数小于在tMap出现的次数
// 则当前window中的子串不满足条件,count--
if (tMap.containsKey(sLeftChar) && window.get(sLeftChar) < tMap.get(sLeftChar)) {
count--;
}
//左指针右移
left++;
}
//右指针右移
right++;
}
return result[0] == -1 ? "" : s.substring(result[1], result[2] + 1);
}
}
使用HashMap存入字符,并记录存入的次数
// 使用HashMap存入次数的方法1111111111111111111111111111111111111
// for (int i = 0; i < t.length(); i++) {
// char tChar = t.charAt(i);
// if (tMap.containsKey(tChar)) {
// tMap.put(tChar, tMap.get(tChar) + 1);
// } else {
// tMap.put(tChar, 1);
// }
// }
// 使用HashMap存入次数的方法222222222222222222222222222222222222
for (int i = 0; i < t.length(); i++) {
int num = tMap.getOrDefault(t.charAt(i), 0);
tMap.put(t.charAt(i), num + 1);
}
Integer类型进行==比较存在的问题