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

/**
 * Created by lxw, liwei4939@126.com on 2017/11/1.
 * 给定字符串str1和str2,求str1中子串含有str2所有字符的最小子串长度
 */
public class minSubstring {

    public int minLength(String str1, String str2){
        if(str1 == null || str2 ==null || str1.length() < str2.length()){
            return 0;
        }
        char[] chas1 = str1.toCharArray();
        char[] chas2 = str2.toCharArray();
        int[] map = new int[256];
        for (int i=0; i< chas2.length; i++){
            map[chas2[i]]++;
        }
        int left= 0;
        int right = 0;
        int minLen =Integer.MAX_VALUE;
        int match =chas2.length;
        while (right != chas1.length){
            map[chas1[right]]--;
            if(map[chas1[right]] >= 0){
                match--;
            }
            if(match == 0){
                while (map[chas1[left]] < 0){
                    map[chas1[left++]]++;
                }
                minLen = Math.min(minLen, right - left + 1);
                match++;
                map[chas1[left++]]++;
            }
            right++;
        }
        return minLen == Integer.MAX_VALUE ? 0 :minLen;
    }

    public static void main(String[] args){
        minSubstring tmp = new minSubstring();

        String str1 = "abcde";
        String str2 = "ac";
        System.out.println(tmp.minLength(str1, str2));

        String str3 = "12345";
        String str4 = "344";
        System.out.println(tmp.minLength(str3, str4));
    }
}

可以使用滑动窗口的思想来解决该问题。具体步骤如下: 1. 定义两个指针left和right,分别表示滑动窗口的左右端点,初始值均为0。 2. 定义一个字典need,用于记录str2每个字符出现的次数。 3. 定义一个计数器count,用于记录滑动窗口已经包含了str2多少个不同的字符。 4. 定义一个变量min_len,用于记录最小的包含str2所有字符子串长度,初始值为正无穷大。 5. 开始循环,当右指针小于str1长度时: a. 如果str1[right]在need出现过,将need[str1[right]]的值减一,并判断need[str1[right]]是否等于0,如果是,则将count加一。 b. 将右指针右移一位。 c. 当count等于need的长度时,说明滑动窗口已经包含了str2的所有字符,计算当前子串长度,并将min_len更新为当前子串长度和min_len的较小值。 d. 如果str1[left]在need出现过,将need[str1[left]]的值加一,并判断need[str1[left]]是否大于0,如果是,则将count减一。 e. 将左指针右移一位。 6. 返回min_len即可。 代码实现如下: ``` def min_substring(str1, str2): need = {} for ch in str2: need[ch] = need.get(ch, 0) + 1 left = right = 0 count = 0 min_len = float('inf') while right < len(str1): if str1[right] in need: need[str1[right]] -= 1 if need[str1[right]] == 0: count += 1 right += 1 while count == len(need): if right - left < min_len: min_len = right - left if str1[left] in need: need[str1[left]] += 1 if need[str1[left]] > 0: count -= 1 left += 1 return min_len ``` 测试代码: ``` print(min_substring('abcd', 'bc')) # 2 print(min_substring('adbecf', 'abc')) # 3 print(min_substring('a', 'a')) # 1 print(min_substring('aaaaa', 'a')) # 1 print(min_substring('ab', 'a')) # 1 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值