Leetcode 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".

使用一个map 来储存 字符 和 在 t 中出现次数的映射关系。然后要用到two pointers 来保持一个 window,cnt 来表示 t 中 所对应数,例子中 如果 cnt 是3, 表示 T 被全部覆盖。用start 来记录minLength 的 左边界。


public String minWindow(String s, String t) {
        if (s == null || s.length() == 0) return "";
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < t.length(); i++) {
            char c = t.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        int l = 0;
        int cnt = 0;
        int start = 0;
        int minLength = s.length() + 1;
        for (int r = 0; r < s.length(); r++) {
            if (map.containsKey(s.charAt(r))) {
                map.put(s.charAt(r), map.get(s.charAt(r)) - 1);
                if (map.get(s.charAt(r)) >= 0) cnt++;
                while (cnt == t.length()) {
                    if (r - l + 1 < minLength) {
                        minLength = r - l + 1;
                        start = l;
                    }
                    if (map.containsKey(s.charAt(l))) {
                        map.put(s.charAt(l), map.get(s.charAt(l)) + 1);
                        if (map.get(s.charAt(l)) > 0) cnt--;
                    }
                    l++;
                }
            }
        }
        return minLength > s.length() ? "" : s.substring(start, start + minLength);
    } 






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值