leetcode-76. 最小覆盖子串

76. 最小覆盖子串

题目描述

给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串。

示例:

输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"

题目详见:https://leetcode-cn.com/problems/minimum-window-substring

解法-滑动窗口

第一步

移动right,找到符合条件的窗口

第二步

移动left,减小窗口面积,直到找到无法满足条件,重复第一步

示例

比如

s=ABAACBAB
t=ABC

下面借用一下leetcode官方的图片
在这里插入图片描述
第一步,移动right,找到包含ABC的字符串
在这里插入图片描述
第二步,移动left,减小窗口面积
在这里插入图片描述

难点

这里还有一个问题,就是如何判断对应窗口中包含了t字符串呢?
通过HashMap来保存对应的字符的数量

还有一种特殊情况需要考虑

s="a"
t="aa"
结果:""

上述例子是不满足要求的,不仅要包含对应字符,而且需要数量不少于t中的数量

示例代码

class Solution {
           public String minWindow(String s, String t) {
            Map<Character,Integer> needs=new HashMap();//需要的字符数量
            Map<Character,Integer> map=new HashMap();//当前的字符数量
            for(int i=0;i<t.length();i++){
                if(!needs.containsKey(t.charAt(i))){
                    needs.put(t.charAt(i),1);

                }else needs.put(t.charAt(i),needs.get(t.charAt(i))+1);
            }
            String res=null;
            int match=0;//表示匹配成功字符数
            int i=0;
            for(int j=0;j<s.length();j++){
                char ch=s.charAt(j);
                if(needs.containsKey(ch)){
                    int count=1;
                    if(map.containsKey(ch))count=map.get(ch)+1;
                    map.put(ch,count);
                    if(count==needs.get(ch))match++;
                    while(match==needs.size()){
                        //System.out.println(i+" "+j);
                        while(!needs.containsKey(s.charAt(i))) i++; //将i移动到对应匹配元素
                        if( res==null||j-i<res.length()) res=s.substring(i,j+1);
                      //  System.out.println(i+"*"+j);
                        char ch2=s.charAt(i);
                        int num= map.get(ch2);
                        if(num==1) map.remove(ch2);
                        else map.put(ch2,num-1);
                        if(num-1<needs.get(ch2)) match--;
                        i++;
     
                    }
                }
            }
          if(res==null) return "";

            return res;
        }

}

i表示left指针,j表示right指针

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值