【Hot100】LeetCode—76. 最小覆盖子串



1- 思路

滑动窗口+双指针+哈希表

  • 哈希表的目的:用于存放 t 中的所有出现字符的频率;再判断 **s** 中字符出现的频率
  • 滑动窗口:维护 对于 s 字符串操作的滑动窗口,利用指针 ij 来遍历

2- 实现

⭐76. 最小覆盖子串——题解思路

在这里插入图片描述

class Solution {
    public String minWindow(String s,String t){
        // 定义两个HashMap
        HashMap<Character,Integer> hs = new HashMap<>();
        HashMap<Character,Integer> ht = new HashMap<>();
        // 定义count
        int count = 0;
        String res = "";
        // 初始化
        for(int i = 0;i < t.length();i++){
            char c = t.charAt(i);
            ht.put(c,ht.containsKey(c)? ht.get(c)+1:1);
        }

        // 遍历 s
        for(int i = 0 ,j=0 ; j<s.length();j++){
            char c = s.charAt(j);
            hs.put(c,hs.containsKey(c) ? hs.get(c)+1:1);

            // 判断合法
            if(ht.containsKey(c) && hs.get(c) <= ht.get(c)) count++;
            // 缩小区间
            while (i <= j && (!ht.containsKey(s.charAt(i)) || hs.get(s.charAt(i)) > ht.get(s.charAt(i)))){
                hs.put(s.charAt(i),hs.get(s.charAt(i))-1);
                i++;
            }   
            // 收集结果
            if(count==t.length() && (res.length() > (j-i+1) || res.length()<1)){
                res = s.substring(i,j+1);
            }
        }
        return res;
    }
}

3- ACM实现

public class minWindow {


    public static String minWindow(String s,String t){
        // 定义两个HashMap
        HashMap<Character,Integer> hs = new HashMap<>();
        HashMap<Character,Integer> ht = new HashMap<>();
        // 定义count
        int count = 0;
        String res = "";
        // 初始化
        for(int i = 0;i < t.length();i++){
            char c = t.charAt(i);
            ht.put(c,ht.containsKey(c)? ht.get(c)+1:1);
        }

        // 遍历 s
        for(int i = 0 ,j=0 ; j<s.length();j++){
            char c = s.charAt(j);
            hs.put(c,hs.containsKey(c) ? hs.get(c)+1:1);

            // 判断合法
            if(ht.containsKey(c) && hs.get(c) <= ht.get(c)) count++;
            // 缩小区间
            while (i <= j && (!ht.containsKey(s.charAt(i)) || hs.get(s.charAt(i)) > ht.get(s.charAt(i)))){
                hs.put(s.charAt(i),hs.get(s.charAt(i))-1);
                i++;
            }
            // 收集结果
            if(count==t.length() && (res.length() > (j-i+1) || res.length()<1)){
                res = s.substring(i,j+1);
            }
        }
        return res;
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入字符串1");
        String s = sc.nextLine();
        System.out.println("输入字符串2");
        String t = sc.nextLine();
        System.out.println("结果是"+minWindow(s,t));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值