-
Notifications
You must be signed in to change notification settings - Fork 0
/
question17.go
53 lines (45 loc) · 854 Bytes
/
question17.go
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
44
45
46
47
48
49
50
51
52
53
package chapter03
func findTheShortestSubstring(s, t string) string {
// Count all the runes in t.
counts := make(map[rune]int)
for _, r := range t {
counts[r]++
}
// Find the min start and length.
short, length, start, end := 0, 0, 0, 0
for start < len(s) {
r := rune(s[start])
if _, ok := counts[r]; !ok {
start++
continue
}
if end < start {
end = start
}
for end < len(s) {
r2 := rune(s[end])
if c, ok := counts[r2]; ok {
counts[r2] = c - 1
}
if allValueIsBelowZero(counts) {
if length == 0 || end-start+1 < length {
length = end - start + 1
short = start
}
break
}
end++
}
counts[r]++
start++
}
return s[short : short+length]
}
func allValueIsBelowZero(counts map[rune]int) bool {
for _, v := range counts {
if v > 0 {
return false
}
}
return true
}