1- 思路
滑动窗口+双指针+哈希表
- 哈希表的目的:用于存放
t
中的所有出现字符的频率;再判断 **s**
中字符出现的频率 - 滑动窗口:维护 对于
s
字符串操作的滑动窗口,利用指针 i
和 j
来遍历
2- 实现
⭐76. 最小覆盖子串——题解思路
class Solution {
public String minWindow(String s,String t){
HashMap<Character,Integer> hs = new HashMap<>();
HashMap<Character,Integer> ht = new HashMap<>();
int count = 0;
String res = "";
for(int i = 0;i < t.length();i++){
char c = t.charAt(i);
ht.put(c,ht.containsKey(c)? ht.get(c)+1:1);
}
for(int i = 0 ,j=0 ; j<s.length();j++){
char c = s.charAt(j);
hs.put(c,hs.containsKey(c) ? hs.get(c)+1:1);
if(ht.containsKey(c) && hs.get(c) <= ht.get(c)) count++;
while (i <= j && (!ht.containsKey(s.charAt(i)) || hs.get(s.charAt(i)) > ht.get(s.charAt(i)))){
hs.put(s.charAt(i),hs.get(s.charAt(i))-1);
i++;
}
if(count==t.length() && (res.length() > (j-i+1) || res.length()<1)){
res = s.substring(i,j+1);
}
}
return res;
}
}
3- ACM实现
public class minWindow {
public static String minWindow(String s,String t){
HashMap<Character,Integer> hs = new HashMap<>();
HashMap<Character,Integer> ht = new HashMap<>();
int count = 0;
String res = "";
for(int i = 0;i < t.length();i++){
char c = t.charAt(i);
ht.put(c,ht.containsKey(c)? ht.get(c)+1:1);
}
for(int i = 0 ,j=0 ; j<s.length();j++){
char c = s.charAt(j);
hs.put(c,hs.containsKey(c) ? hs.get(c)+1:1);
if(ht.containsKey(c) && hs.get(c) <= ht.get(c)) count++;
while (i <= j && (!ht.containsKey(s.charAt(i)) || hs.get(s.charAt(i)) > ht.get(s.charAt(i)))){
hs.put(s.charAt(i),hs.get(s.charAt(i))-1);
i++;
}
if(count==t.length() && (res.length() > (j-i+1) || res.length()<1)){
res = s.substring(i,j+1);
}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入字符串1");
String s = sc.nextLine();
System.out.println("输入字符串2");
String t = sc.nextLine();
System.out.println("结果是"+minWindow(s,t));
}
}