website/content.en/ChapterFour/0001~0099/0076.Minimum-Window-Substring.md
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:
Given a source string s and another string T, find a window in the source string that contains all characters from any permutation and combination of the string T. The window may contain characters not in T. If multiple such windows exist, output the smallest window in the result. If no such window can be found, output an empty string.
This is a sliding window problem. During the window sliding process, continuously include the string T until all characters of string T are fully included, then record the positions of the left and right boundaries of the window and the window size. Continuously update this valid window and the minimum window size each time. Finally, output the result.
package leetcode
func minWindow(s string, t string) string {
if s == "" || t == "" {
return ""
}
var tFreq, sFreq [256]int
result, left, right, finalLeft, finalRight, minW, count := "", 0, -1, -1, -1, len(s)+1, 0
for i := 0; i < len(t); i++ {
tFreq[t[i]-'a']++
}
for left < len(s) {
if right+1 < len(s) && count < len(t) {
sFreq[s[right+1]-'a']++
if sFreq[s[right+1]-'a'] <= tFreq[s[right+1]-'a'] {
count++
}
right++
} else {
if right-left+1 < minW && count == len(t) {
minW = right - left + 1
finalLeft = left
finalRight = right
}
if sFreq[s[left]-'a'] == tFreq[s[left]-'a'] {
count--
}
sFreq[s[left]-'a']--
left++
}
}
if finalLeft != -1 {
result = string(s[finalLeft : finalRight+1])
}
return result
}