Leetcode#76||Minimum Window Substring

198 篇文章 0 订阅
25 篇文章 0 订阅


public class Solution {
    public String minWindow(String s, String t) {
        String result = "";
        
        if (s == null || t == null || s.length() < t.length()) {
            return result;
        }
        
        int tLen = t.length();
        int left = 0;
        //int right = 0;
        int count = 0;
        int minLen = Integer.MAX_VALUE;
        
        Map<Character, Integer> target = new HashMap<Character, Integer>();
        for (int i = 0; i < tLen; i++) {
            char c = t.charAt(i);
            
            if (target.containsKey(c)) {
                target.put(c, target.get(c) + 1);
            } else {
                target.put(c, 1);
            }
        }
        
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        
        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            
            if (target.containsKey(c)) {
                
                if (map.containsKey(c)) {
                    
                    if (map.get(c) < target.get(c)) {
                        count++;
                    }
                    
                    map.put(c, map.get(c) + 1);
                } else {
                    count++;
                    map.put(c, 1);
                }
            }
            
            if (count == tLen) {
                
                char prev = s.charAt(left);
                
                while (!map.containsKey(prev) || map.get(prev) > target.get(prev)) {
                    
                    if (map.containsKey(prev) && map.get(prev) > target.get(prev)) {
                        map.put(prev, map.get(prev) - 1);
                    }
                    left++;
                    prev = s.charAt(left);
                }
                
                if (right - left + 1 < minLen) {
                    result = s.substring(left, right + 1);
                    minLen = right - left + 1;
                }
                
                count--;
                map.put(prev, map.get(prev) - 1);
                left++;
            }
        }
        
        return result;        
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值