Sunday, November 16, 2014

[LeetCode] 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 emtpy string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

思路:

1. 如果S[i:j]是min window,那么S[i], S[j]必然也在T中。
2. 对于任意S[i]要检查是否也在T中,需要将T的所有字符建立一个hash table。T中可能有重复字符,所以key = T[i], val = freq of (T[i])。
3. 先找到第一个window包含T
4. 扫描S[i]
若S[i]不在T中,跳过。
若S[i]在T中,freq of (S[i]) - 1,并且match的长度+1

ADOBECODEBANC
ADOBECODEBANC
ADOBECODEBANC
ADOBECODEBANC

No comments:

Post a Comment