2021-12-17 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 ““

给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “”

给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。
示例 1:
输入:s = “ADOBECODEBANC”, t = “ABC” 输出:“BANC”
示例 2:
输入:s = “a”, t = “a” 输出:“a”

首先感觉此题没有意义,
通过答案设计十分巧妙。学习一下。

package com.javacase;

public class LearnForEveryDay {
    public static void main(String[] args) {
        String s="ADOBECODEBANC";
        String t="ABC";
        LearnForEveryDay main = new LearnForEveryDay();
        System.out.println(LearnForEveryDay.minWindow(s, t));
        String ss="a";
        String tt="a";
        System.out.println(LearnForEveryDay.minWindow(ss, tt));
    }

    public static String minWindow(String s, String t) {
        //创建int 数组ta 长度128 默认数值均为0
        int[] ta = new int[128];
        //创建int 数组sa 长度128 默认数值均为0
        int[] sa = new int[128];
        int min = Integer.MAX_VALUE;
        String minWin = "";
        // 循环字符串t的每个字符,并设置ta数组对应的值为1
        for (int i = 0; i < t.length(); i++) {
            ta[t.charAt(i)]++; // t.chartAt(0)=A; char类型的A 转换为int时值为65;  即ta[65]默认为0; ta[65]++ 为1
        }
        int count = 0;
        int end = 0;
        int start = 0;
        while (end < s.length()) {
            if (ta[s.charAt(end)] != 0) {
                if (sa[s.charAt(end)] < ta[s.charAt(end)]) {
                    count++;
                }
                sa[s.charAt(end)]++;
            }
            if (count == t.length()) {
                while (ta[s.charAt(start)] == 0 || sa[s.charAt(start)] > ta[s.charAt(start)]) {
                    if (sa[s.charAt(start)] > ta[s.charAt(start)]) {
                        sa[s.charAt(start)]--;
                    }
                    start++;
                }
                if (end - start + 1 < min) {
                    minWin = s.substring(start, end + 1);
                    min = end - start + 1;
                }
            }
            end++;
        }
        return minWin;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EngineerForSoul

你的鼓励是我孜孜不倦的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值