1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// @Title: 含有所有字符的最短字符串 (含有所有字符的最短字符串)
// @Author: 15816537946@163.com
// @Date: 2022-03-26 10:39:13
// @Runtime: 12 ms
// @Memory: 2.7 MB
func minWindow(s string, t string) string {
	need := make(map[byte]int)
	for i := range t {
		need[t[i]]++
	}
	needCnt := len(t)
	ret := [2]int{0, math.MaxInt32}

	var lo int
	for hi := range s {
		if need[s[hi]] > 0 {
			needCnt--
		}
		need[s[hi]]--

		if needCnt == 0 {
			for true {
				if need[s[lo]] == 0 {
					break
				}
				need[s[lo]]++
				lo++
			}

			if hi-lo < ret[1]-ret[0] {
				ret = [2]int{lo, hi}
			}
			need[s[lo]]++
			needCnt++
			lo++
		}
	}

	if ret[1] > len(s) {
		return ""
	}
	return s[ret[0] : ret[1]+1]
}