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.


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值