LeetCode-017. 含有所有字符的最短字符串

该代码实现了一个方法,用于查找字符串s中包含所有字符串t字符的最短子串。它使用滑动窗口策略,初始化一个计数数组来比较两个字符串的字符差异,并逐步调整窗口大小以找到最小匹配子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • s 和 t 由英文字母组成
class Solution {
    public String minWindow(String s, String t) {

        //窗口包含字符:左移、不包含:右移
        String res = "";
        int ns = s.length();
        int nt= t.length();
        int length=ns;
        if(ns<nt) return "";
        //寻找满足条件的可行窗口
        int[] count = new int[60];
        //记录初始窗口与目标字符串相差哪几个字母
        //如果count[i]大于0 则说明在t中有 在当前窗口没有
        //如果count[i] == 0 则说明t和当前窗口都有
        //如果count[i]小于0 则说明在t中没有 在当前窗口有 ->不需要关注
        for (int i = 0; i < nt; i++) {
            count[t.charAt(i) - 'A'] ++;
            count[s.charAt(i) - 'A'] --;
        }
        if (isContains(count)) return s.substring(0, t.length());
        //窗口一直满足,缩短
        for (int i = t.length(),left=0; i < s.length(); ++ i){
            count[s.charAt(i) - 'A'] -- ;//右移
            while (areAllZero(count)){
                if (length >= i - left + 1) {
                    //更新
                    length = i - left + 1;
                    res = s.substring(left,i+1);
                }
                count[s.charAt(left)-'A']++;//左侧
                left++;
            }
        }
        return res;
    }

    private boolean isContains(int[] count) {
        for (int i : count) {
            if(i>0){
                return false;
            }
        }
        return true;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值