/**
* 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));
}
}
给定字符串str1和str2,求str1中子串含有str2所有字符的最小子串长度
最新推荐文章于 2024-08-27 13:02:10 发布