输入包括两行,第一行一个字符串,代表str1,第二行也是一个字符串,代表str2
。
输出str1的字串中含有str2所有字符的最小字符串长度,如果不存在请输出0。
abcde ac
3
“abc”中包含“ac”,且“abc”是所有满足条件中最小的。
12345 344
0
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.HashMap; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] str1 = br.readLine().toCharArray(); char[] str2 = br.readLine().toCharArray(); HashMap<Character, Integer> termFreq = new HashMap<>(); for(int i = 0; i < str2.length; i++) termFreq.put(str2[i], termFreq.getOrDefault(str2[i], 0) + 1); int left = 0, right = 0; int debt = str2.length; // 刚开始欠str2长度的字符 int minLen = str1.length + 1; while(right < str1.length){ if(!termFreq.containsKey(str1[right])) { right ++; // 跳过不相关的字符 continue; } termFreq.put(str1[right], termFreq.getOrDefault(str1[right], 0) - 1); if(termFreq.get(str1[right]) >= 0) debt --; if(debt == 0){ if(!termFreq.containsKey(str1[left])){ left ++; // 跳过不相关的字符 continue; } // 负债小于0的词是多余的,先去掉 while(termFreq.get(str1[left]) < 0){ termFreq.put(str1[left], termFreq.getOrDefault(str1[left], 0) + 1); left ++; } // 负债为0且无多余词,更新长度 minLen = Math.min(minLen, right - left + 1); termFreq.put(str1[left], termFreq.getOrDefault(str1[left], 0) + 1); debt ++; left ++; } right ++; } minLen = Math.min(minLen, right - left + 1); System.out.println(minLen == str1.length + 1? 0: minLen); } }