Notes title leetcode brush (Golang) -. 76 Minimum Window Substring

76. Minimum Window Substring

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = “ADOBECODEBANC”, T = “ABC”
Output: “BANC”
Note:

If there is no such window in S that covers all characters in T, return the empty string “”.
If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

Problem-solving ideas

func minWindow(s string, t string) string {
	if len(s) == 0 || len(t) == 0 {
		return ""
	}
	goalMap := make(map[string]int)
	for _, v := range t {
		goalMap[string(v)]++
	}

	res, minLen := "", math.MaxInt32
	l, cnt, golaSize := 0, 0, len(t)
	currMap := make(map[string]int)
	for r := 0; r < len(s); r++ {
		key := string(s[r])
		if goalMap[key] <= 0 {
			continue
		}

		if currMap[key] < goalMap[key] {
			cnt++
		}
		currMap[key]++
		if cnt == golaSize {
			k := string(s[l])
			for goalMap[k] <= 0 || currMap[k] > goalMap[k] {
				if goalMap[k] > 0 && currMap[k] > goalMap[k] {
					currMap[k]--
				}
				l++
				k = string(s[l])
			}
			if r-l+1 < minLen {
				minLen = r - l + 1
				res = s[l : r+1]
			}
		}

	}
	return res
}
Published 65 original articles · won praise 0 · Views 356

Guess you like

Origin blog.csdn.net/weixin_44555304/article/details/104287130