LeetCode-Algorithms-[Hard]76. 最小覆盖子串

给你一个字符串 S、一个字符串 T 。请你设计一种算法,可以在 O(n) 的时间复杂度内,从字符串 S 里面找出:包含 T 所有字符的最小子串。

示例:

输入:S = “ADOBECODEBANC”, T = “ABC”
输出:“BANC”

提示:

如果 S 中不存这样的子串,则返回空字符串 “”。
如果 S 中存在这样的子串,我们保证它是唯一的答案。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-window-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


    private final char BEGIN_CHAR = 'A';

    private final int ALPHABET_SIZE = 'z' - BEGIN_CHAR + 1;
    // ASCII码对照表
    // https://tool.ip138.com/ascii_code/

    private final String NULL_STR = "";

    public String minWindow(String s, String t) {
        if (s == null || t == null) {
            return NULL_STR;
        }
        int[] sCount = new int[ALPHABET_SIZE];
        int[] tCount = new int[ALPHABET_SIZE];

        int l_s = s.length();
        int l_t = t.length();
        if (l_t == 0) {
            return NULL_STR;
        }

        int alphaCount = 0;

        for (int i = 0; i < l_t; ++i) {
            int index = t.charAt(i) - BEGIN_CHAR;
            if (tCount[index] == 0) {
                ++alphaCount;
            }
            ++tCount[index];
        }
        int l = 0;
        int r = 0;
        int count = 0;
        int begin = -1;
        int maxLength = l_t == Integer.MAX_VALUE ? l_s : l_s + 1;
        int length = maxLength;
        while (r < l_s) {
            char c = s.charAt(r);
            int index = c - BEGIN_CHAR;
            if (tCount[index] > 0) {
                ++sCount[index];
                if (sCount[index] == tCount[index]) {
                    ++count;
                }
            }
            while (count == alphaCount) {
                int currentLength = r - l + 1;
                if (currentLength < length) {
                    begin = l;
                    length = currentLength;
                }
                c = s.charAt(l);
                ++l;
                index = c - BEGIN_CHAR;
                if (tCount[index] > 0) {
                    if (tCount[index] == sCount[index]) {
                        --count;
                    }
                    --sCount[index];
                }
            }
            ++r;
        }
        return maxLength == length ? NULL_STR : s.substring(begin, begin + length);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值