给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串。
1 /*
2 * https://leetcode-cn.com/problems/minimum-window-substring/
3 *
4 * 给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串。
5 * */
6 import java.util.HashMap;
7
8 public class code076_MinimumWindowSubstring
9 {
10 public String minWindow(String s, String t) {
11 if (s.length() == 0 || t.length() == 0){
12 return "";
13 }
14 int start = 0, minLen = Integer.MAX_VALUE;
15 HashMap<Character, Integer> window = new HashMap<>();
16 HashMap<Character, Integer> needs = new HashMap<>();
17 int left = 0, right = 0;
18 for (int i = 0; i < t.length(); i++)
19 {
20 needs.put(t.charAt(i), needs.getOrDefault(t.charAt(i), 0) + 1);
21 }
22 int match = 0;
23 while (right < s.length()){
24 char c = s.charAt(right);
25 if(needs.containsKey(c)){
26 window.put(c, window.getOrDefault(c, 0) + 1);
27 if(needs.get(c).compareTo(window.get(c)) == 0){
28 match++;
29 }
30 }
31 right++;
32
33 while (match == needs.size()){
34 if(right - left < minLen){
35 start = left;
36 minLen = right - left;
37 System.out.println(minLen);
38 }
39 char c1 = s.charAt(left);
40 if(needs.containsKey(c1)){
41 int num = window.get(c1);
42 window.put(c1, num - 1);
43 // System.out.println(String.valueOf(right) + ";" + c1 + ";" + String.valueOf(window.get(c1)));
44 if(window.get(c1) < needs.get(c1))
45 match--;
46 }
47 left++;
48 }
49 }
50 return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen);
51 }
52 public static void main(String[] args){
53 code076_MinimumWindowSubstring minimumWindowSubstring = new code076_MinimumWindowSubstring();
54 System.out.println(minimumWindowSubstring.minWindow("EBBANCF", "ABC"));
55 System.out.println(minimumWindowSubstring.minWindow("ADOBECODEBANC", "ABC"));
56 System.out.println(minimumWindowSubstring.minWindow("a", "aa"));
57
58 }
59 }
给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。
1 import java.util.ArrayList;
2 import java.util.HashMap;
3 import java.util.List;
4
5 public class code438_FindAllAnagramsinaString
6 {
7 public List<Integer> findAnagrams(String s, String p) {
8 List<Integer> list = new ArrayList<>();
9 if (s.length() == 0 || p.length() == 0){
10 return list;
11 }
12 HashMap<Character, Integer> window = new HashMap<>();
13 HashMap<Character, Integer> needs = new HashMap<>();
14 int left = 0, right = 0;
15 for (int i = 0; i < p.length(); i++)
16 {
17 needs.put(p.charAt(i), needs.getOrDefault(p.charAt(i), 0) + 1);
18 }
19 int match = 0;
20 while (right < s.length()){
21 char c = s.charAt(right);
22 if(needs.containsKey(c)){
23 window.put(c, window.getOrDefault(c, 0) + 1);
24 if(needs.get(c).compareTo(window.get(c)) == 0){
25 match++;
26 }
27 }
28 right++;
29
30 while (match == needs.size()){
31 if(right - left == p.length()){
32 list.add(left);
33 }
34 char c1 = s.charAt(left);
35 if(needs.containsKey(c1)){
36 int num = window.get(c1);
37 window.put(c1, num - 1);
38 if(window.get(c1) < needs.get(c1))
39 match--;
40 }
41 left++;
42 }
43 }
44 return list;
45 }
46 }