[Leetcode] Two pointer-- 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).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC"
.
Note:
If there is no such window in S that covers all characters in T, return the empty string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Solution:
windows problem: use two pointer, fix left and move right pointer, traverse source s and find the current windows containing t,
then move the left point to next point to update the current window length to get the minimum window
1 targetHash = {} #store the target character counter 2 3 for c in t: 4 if c not in targetHash: 5 targetHash[c] = 1 6 else: 7 targetHash[c] += 1 8 9 srcHash = {} 10 11 count = 0 #decide when T matched in S 12 left = 0 13 right = 0 14 minWindLen = 2**32 15 minStart = 0 16 17 #print ("target hash: ", targetHash) 18 while (right < len(s)): 19 20 if s[right] in targetHash and targetHash[s[right]] > 0: 21 if s[right] not in srcHash: 22 srcHash[s[right]] = 1 23 else: 24 srcHash[s[right]] += 1 25 if (srcHash[s[right]] <= targetHash[s[right]]): 26 count += 1 27 28 if count == len(t): 29 30 31 while (s[left] not in targetHash or (s[left] in srcHash and s[left] in targetHash and srcHash[s[left]] > targetHash[s[left]])): 32 if s[left] in targetHash: 33 srcHash[s[left]] -= 1 34 left += 1 35 36 if minWindLen > (right-left+1): 37 minWindLen = right-left+1 38 minStart = left 39 40 41 right += 1 42 43 return s[minStart: minStart+minWindLen] if minWindLen <= len(s) else ""