**LeetCode-Minimum Window Substring

15 篇文章 0 订阅
9 篇文章 0 订阅

这种题都是hashmap加two pointers思想 但是移动start pointer的rules不一样 以及判断是否包含了所有的字母找到了答案的方法也不太一样

这个题也是先统计总共需要哪些字母 需要多少个 然后开始扫

同样是要找到有效count等于需要的总count之后表示找到了答案 然后这个题的start指针记得要挪动到下一个valid字母处

public class Solution {
    public String minWindow(String s, String t) {
        HashMap<Character, Integer> hist = new HashMap<Character, Integer>();
        for ( int i = 0; i < t.length(); i ++ ){
            if ( hist.containsKey ( t.charAt( i )))
                hist.put ( t.charAt( i ), hist.get (t.charAt(i)) + 1);
            else
                hist.put ( t.charAt( i ), 1 );
        }
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int start = 0;
        String minSub = "";
        int minLen = Integer.MAX_VALUE;
        int count = 0;
        for ( int i = 0; i < s.length(); i ++ ){
            char c = s.charAt ( i );
            if ( hist.containsKey ( c ) ){
                if ( map.containsKey( c ) )
                    map.put ( c, map.get ( c ) + 1 );
                else
                    map.put ( c, 1 );
                if ( map.get ( c ) <= hist.get ( c ))
                    count ++;
            }
            if ( count == t.length()){
               while( !hist.containsKey(s.charAt(start)) || map.get(s.charAt(start)) > hist.get(s.charAt(start))){
                        if( map.containsKey(s.charAt(start)))
                            map.put(s.charAt(start), map.get(s.charAt(start))-1);
                        start++;
                }
              if ( i - start + 1 < minLen ){
                    minLen = i - start + 1;
                    minSub = s.substring( start, i + 1 );
                }
                count --;
                map.put(s.charAt(start), map.get(s.charAt(start))-1);
                start ++;
            }
        }
        return minSub;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值