let 76. Minimum Window Substring

 Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example,
S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC".

Note:
If there is no such window in S that covers all characters in T, return the empty string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. 

主题思想: 总体思路如下: 利用hashMap , 2. 利用两个指针,进行夹逼, 找到最小的窗口。

具体细节:1. 对 t 中的字符进行hash统计出现的次数。 对于未在t中出现的,初始化为0. 这个意思是把所有的字符都统计起来。 初始化一个数字num 为t的长度
2. 遍历 s 中 字符,判断是否大于0,如果大于0 ,则在t中出现过,num–; 表示还有num-1个没有包含。最后无论是否在t中出现,都要对map进行更新 -1。
3. 如果num==0表示已经全部包含t中所有字符,但是可能有多余的无关字符,或者冗余字符,这时移动左边指针,缩小窗口,如果字符的value值是0,则表示找到一个t中字符,num++; 更新使num增加,变成非法。 并所有value+1

具体AC代码:

总结起来 end下标右移扩大窗口,所有value值 每次减

class Solution {
    public String minWindow(String s, String t) {

        HashMap<Character,Integer> wordCounter=new HashMap<Character,Integer>();

        int len=t.length();
        for(int i=0;i<len;i++) wordCounter.put(t.charAt(i),wordCounter.getOrDefault(t.charAt(i),0)+1);

        int begin=0,end=0;
        int num=len;

        int mini=Integer.MAX_VALUE;
        String ans="";
        while(end<s.length()){

            if(wordCounter.getOrDefault(s.charAt(end),-2)>0){
                num--; // find the character in t  
            }
            //here make all character not in t put with default -1
            wordCounter.put(s.charAt(end),wordCounter.getOrDefault(s.charAt(end),0)-1);
            while(num==0){

                //update ans
                if(end-begin+1<mini){
                    mini=end-begin+1;
                    ans=s.substring(begin,end+1);
                }

                //because begin<end so  s.charAt(begin) must in wordCounter so can use get not need getOrDefault
                if(wordCounter.get(s.charAt(begin))==0){  // make invalid  ,so find the miniums
                    num++;
                }
                wordCounter.put(s.charAt(begin),wordCounter.get(s.charAt(begin))+1);
                begin++;
            }
            end++;
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值