76. 最小覆盖子串
题目
给你一个字符串 S、一个字符串 T 。请你设计一种算法,可以在 O(n) 的时间复杂度内,从字符串 S 里面找出:包含 T 所有字符的最小子串。
示例:
输入:S = “ADOBECODEBANC”, T = “ABC”
输出:“BANC”
思路
还是滑动窗口的思想,具体参考https://leetcode-cn.com/problems/minimum-window-substring/solution/zui-xiao-fu-gai-zi-chuan-by-leetcode-solution/
我下面的原始代码就是用这种思想写的,没有经过优化,所以有些慢
代码
我的代码,很慢
//用两个Map来表示s和t,分别统计它们中每个char出现的次数
//check函数复制检查S和T是否相等
public static boolean check(Map<Character,Integer> S, Map<Character,Integer> T) {
boolean con = true;
for(char c:T.keySet()){
if(S.containsKey(c)){
con =con && S.get(c)>=T.get(c);
}else {
return false;
}
}
return con;
}
// 主函数
public static String minWindow(String s, String t) {
int n = s.length();
if(n<t.length()){
return "";
}
//定义两个Map,用来储存s和t中char是否出现以及出现的次数
//之前用了两个HashSet,它只可以比较char是否出现,但无法计算次数,如果t=“AAA",那在Set中
//就只会有一个值A,这对于后面的判断会造成错误的误导;对于滑动窗口中的s的值,也是这样,
//都会产生误导
Map<Character,Integer> Ms = new HashMap<>();
Map<Character,Integer> Mt = new HashMap<>();
//先对Mt进行初始化
for(int j=0;j<t.length();j++){
if(Mt.containsKey(t.charAt(j))){
Mt.put(t.charAt(j),Mt.get(t.charAt(j))+1);
}else{
Mt.put(t.charAt(j),1);
}
}
int min = Integer.MAX_VALUE;
String r = "";
int l = 0;
int i = 0;
//这里更像双指针,l是后面的指针,i是前面的指针
while (l < n && i < n) {
if (i < n) {
if(Ms.containsKey(s.charAt(i))){
Ms.put(s.charAt(i),Ms.get(s.charAt(i))+1);
}else{
Ms.put(s.charAt(i),1);
}
i++;
}
while (check(Ms, Mt)) {
if (min > i - l ) {
min = i - l ;
r = s.substring(l, i);
}
if(Ms.get(s.charAt(l))==1){
Ms.remove(s.charAt(l));
}else{
Ms.put(s.charAt(l),Ms.get(s.charAt(l))-1);
}
l++;
}
}
//当前面的指针i走到头了,不能再走了,继续走后面的指针l,不然会产生遗漏
if (l < n) {
while (check(Ms, Mt)) {
if (min > i - l ) {
min = i - l ;
r = s.substring(l, i);
}
if(Ms.get(s.charAt(l))==1){
Ms.remove(s.charAt(l));
}else{
Ms.put(s.charAt(l),Ms.get(s.charAt(l))-1);
}
l++;
}
}
return r;
}
优化代码
用int数组来作为哈希表,既能判断元素是否存在,又能得到具体的元素个数,访问时间也是O(1),学到了
public static String minWindow(String s, String t) {
if (s == null || s == "" || t == null || t == "" || s.length() < t.length()) {
return "";
}
//用来统计t中每个字符出现次数
int[] needs = new int[128];
//用来统计滑动窗口中每个字符出现次数
int[] window = new int[128];
for (int i = 0; i < t.length(); i++) {
needs[t.charAt(i)]++;
}
int left = 0;
int right = 0;
String res = "";
//目前有多少个字符
//这是算法的精髓,不需要每次移动窗口都比较两个哈希数组是否一致,只有当count满足条件
//才去比较,节省了很多时间
int count = 0;
//用来记录最短需要多少个字符。
int minLength = s.length() + 1;
while (right < s.length()) {
char ch = s.charAt(right);
window[ch]++;
if (needs[ch] > 0 && needs[ch] >= window[ch]) {
count++;
}
//移动到不满足条件为止
while (count == t.length()) {
ch = s.charAt(left);
if (needs[ch] > 0 && needs[ch] >= window[ch]) {
count--;
}
if (right - left + 1 < minLength) {
minLength = right - left + 1;
res = s.substring(left, right + 1);
}
window[ch]--;
left++;
}
right++;
}
return res;
}