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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
| package main
import "fmt"
func minWindow(s string, t string) string { need := make(map[byte]int) window := make(map[byte]int) for i := 0; i < len(t); i ++ { need[t[i]] ++ }
start, length := 0, len(s) + 1 left, right := 0, 0 for right < len(s) { if _, ok := need[s[right]]; ok { window[s[right]] ++ } for checkWindow(need, window) { if right - left + 1 < length { start = left length = right - left + 1 } if _, ok := need[s[left]]; ok { window[s[left]] -- } left ++ } right ++ }
if length == len(s) + 1 { return "" } return s[start : start + length] }
func checkWindow(need map[byte]int, window map[byte]int) bool { for k, v := range need { if window[k] < v { return false } }
return true }
func minWindow_1(s string, t string) string { need := make(map[byte]int) window := make(map[byte]int) for i := 0; i < len(t); i ++ { need[t[i]] ++ }
start, length := 0, len(s) + 1 left, right, valid := 0, 0, 0 for right < len(s) { c := s[right] right ++ if _, ok := need[c]; ok { window[c] ++ if window[c] == need[c] { valid ++ } } for valid == len(need) { if right - left < length { start = left length = right - left } d := s[left] left ++ if _, ok := need[d]; ok { if window[d] == need[d] { valid -- } window[d] -- } } }
if length == len(s) + 1 { return "" } return s[start : start + length] }
func main() { testCases := []struct { s string t string expected string }{ {"ADOBECODEBANC", "ABC", "BANC"}, {"a", "a", "a"}, {"a", "aa", ""}, }
for i, tc := range testCases { result := minWindow(tc.s, tc.t) fmt.Printf("Test Case %d, Input: s = %q, t = %q\n", i+1, tc.s, tc.t) if result == tc.expected { fmt.Printf("Test Case %d, Output: %q, PASS\n", i+1, result) } else { fmt.Printf("Test Case %d, Output: %q, FAIL (Expected: %q)\n", i+1, result, tc.expected) } } }
|