您的位置:首页 > 其它

LeetCode: Minimum Window Substring

2013-05-11 11:19 681 查看
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.

If we have a window, the first letter in this window is a char in T, and the last word in this window is also a char in T, then this window could be the shortest in S.  Continue to sweep in S, if find another char which is also in T, for this char in T, record
the latest appear in the window, replace the earliest appear in this window.  For example:

ADOBEC, A appear in the first place, B in the 4th place and C in the last place, if the next word is A, then the window immediately become BECA,

If the next word is B, the window will become ADOBECB, because we still need an A in this window, but later if A could be replaced, we will know the latest C and latest B's position.

Thus, we need to use a set to remember the latest appearance of each word in this window.  For example,this latest A appears in pos 0, latest B appears in 3, latest C appears in pos 5.  And the set is [0, 3, 5].  After
we continue to sweep, we find another B, it becomes 

ADOBECODEB

The set is [0, 5, 9].  Next we sweep to and find an A, then the set will be [5, 9, 10], and the window will be

CODEBA

If char in T is unique, we could just use an array to record the latest appearance of each char in T.  If not, for each word in T, we need to set-up a queue

My code finishes tests in 540 ms

Ask me for the code if you need
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息