最短包含字符串的长度

给定字符串str1和str2,求str1的字串中含有str2所有字符的最小字符串长度。

输入描述:
输入包括两行,第一行一个字符串,代表str1,第二行也是一个字符串,代表str2。

输出描述:
输出str1的字串中含有str2所有字符的最小字符串长度,如果不存在请输出0。

示例1
输入
abcde
ac
输出
3
说明
“abc”中包含“ac”,且“abc”是所有满足条件中最小的。
示例2
输入
12345
344
输出
0

public class MinLength {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String s1 = scanner.nextLine();
        String s2 = scanner.nextLine();
        System.out.println(getMinLength(s1, s2));
    }
    public static int getMinLength(String s1, String s2){
        if(s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0 || s1.length() < s2.length()){
            return 0;
        }
        char[] array1 = s1.toCharArray();
        char[] array2 = s2.toCharArray();
        int[] map = new int[256];
        /**
         * map中:0 初始值;大于0 欠缺的字符;小于0 不欠缺的字符
         */
        for(int i=0;i<array2.length;i++){
            map[array2[i]]++;
        }
        int left = 0;
        int right = 0;
        int minLength = Integer.MAX_VALUE;
        int match = array2.length;//待匹配的字符数目
        while(right < array1.length){
            /**
             * 初始值 自减后 小于0,变成不欠缺的字符
             * 欠缺的字符 自减后,最小变成 0 初始值
             */
            map[array1[right]]--;
            if(map[array1[right]] >= 0){
                //找到欠缺的字符,match自减,直到match=0,说明所有待匹配的字符都匹配了
                match--;
            }
            if(match == 0){
                /**
                 * 全匹配上了,开始向右移动left
                 * 寻找匹配字符的最左边的位置。
                 * 例如:abcsfdr
                 * 这里找:bcd
                 * 此时,right已经到了d即index=5的位置
                 * 要计算出长度,需要知道,最左边在{bcd}中字符的位置
                 * 所以移动left从index=0开始,直到找到{bcd}中任意字符
                 * 所以left移动到b即index=1,此时最短长度为 5 - 1 + 1 = 5
                 */
                while(map[array1[left]] < 0){
                    /**
                     * 小于0说明不是匹配到的字符,继续右移,直到找到最左边匹配的字符
                     */
                    map[array1[left]]++;
                    left++;
                }
                minLength = Math.min(minLength, right - left + 1);
                /**
                 * 继续往后:让left所指的字符不做匹配
                 * 待匹配的字符数目+1
                 * left所指字符的欠缺值+1
                 * left右移
                 */
                match++;
                map[array1[left]]++;
                left++;
            }
            //right右移
            right++;
        }
        return minLength == Integer.MAX_VALUE ? 0 : minLength;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值