题目: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.

前面两个系列讲了O(N*M)和O(NlogM)的解法。下面讲一下O(N)的。人生可不就是一场不停的战斗么。。。?

实际上leetcode已经有这个的详细解法和介绍了,大家可以看看这里

以下部分我翻译自leetcode上的解说。

注意到前面的解法(O(NlogM))用到了一个hash table,一个队列(二娃:C++解法中使用队列来实现charAppearanceRecorder),一个sorted map,真是要有多复杂有多复杂。在面试中,问题通常来说比较短,代码也大多会不超过50行,所以一定要和面试官交流,让他知道你的想法。如果你的思路比较复杂,面试官可能会给出一些提示。如果你半天都找不到好的方法又闷声不响地在那抠,那就悲剧鸟。

我们下面使用 S = "acbbaca" and T = "aba" 来演示这个算法。基本思路是在遍历S的过程中,使用两个指针(合法window的begin和end索引)和两个table(needToFindhasFound),needToFind保存T中每个字母的个数(二娃:相当于我们的needToFill),hasFound保存当前收集到的每个字母的个数。我们也同时使用一个count变量,用来保存当前收集到的字母总数,但是那些收集过了的字母数并不算在count里面。这样的话,当count等于T.length,那我们就知道遇到一个合法的window了。

我们利用end指针来遍历S,假设当前end指向S中的字母x,如果x是T中的字母,hasFound[x]加一。如果hasFound[x]目前还小于等于needToFind[x](二娃:说明字母x还没有收集全或者刚刚收集全哦),那么我们同时也增加count。当合法window的条件满足,也就是count等于T.length,我们立即递增begin指针,并且保证在递增的过程中始终有count等于T.length。

在递增begin指针的过程中,我们怎么样才能保证“始终有count等于T.length”呢?

假设begin指向字母x,如果hasFound[x]大于了needToFind[x],hasFound[x]减去一,同时递增begin。(二娃:这里很有画面感哦。因为当前遇到的x是冗余的靠左的字母,这里的操作其实等价于前面两个算法中的“删除charAppearanceRecorder中相应的字母的链表头节点”,有点儿像一个是lazy去重,一个是eager去重)否则的话,当前的begin就是window的起始索引了。

接下来我们就可以通过end - begin + 1得到当前window的长度了。这里便可以更新最小window长度。

算法实际上首先找到第一个合法的window,然后在接下来的扫描过程中保持window的合法性(二娃:其实就是count 始终小于等于(当遇到新window)T.length)。

看下面的图图。

i)S = "acbbaca" and T = "aba".

ii)找到第一个合法的window。这里注意我们不能递增begin指针因为hasFound['a'] 等于 needToFind['a'],即2. 如果我们此时递增begin,那就不是合法window了。

iii)找到第二个合法的window。begin指针指向第一个a,hasFound['a']等于3,而needToFind['a']等于2,说明这个a是一个冗余的a,我们递减hasFound['a']同时递增begin。

iv)我们也需要跳过那些不在T中的字母,例如上面的c。现在beging指向了b,hasFound['b']等于2,大于了needToFind['b'],说明这也是一个冗余的b,我们递减hasFound['a']同时递增begin。

v)begin指向b,这时候hasFound['b']等于needToFind['b']。不能再减了,同时begin也不能再次移动了,这里就是一个短window的起点位置。

begin和end都最多前进N次,从而整个算法执行小于2N. 复杂度是O(N)。

上述算法的代码如下:

 public String minWindow3(String S, String T){
HashMap<Character, Integer> needToFill = new HashMap<Character, Integer>();
HashMap<Character, Integer> hasFound = new HashMap<Character, Integer>();
int count = 0;
for(int i = 0; i < T.length(); i++){
if(!needToFill.containsKey(T.charAt(i))){
needToFill.put(T.charAt(i), 1);
hasFound.put(T.charAt(i), 0);
}else {
needToFill.put(T.charAt(i), needToFill.get(T.charAt(i)) + 1);
}
}
int minWinBegin = -1;
int minWinEnd = S.length();
for(int begin = 0, end = 0; end < S.length(); end++){
char c = S.charAt(end);
if(needToFill.containsKey(c)){
hasFound.put(c, hasFound.get(c) + 1);
if(hasFound.get(c) <= needToFill.get(c)){
count++;
}
if(count == T.length()){
while(!needToFill.containsKey(S.charAt(begin)) ||
hasFound.get(S.charAt(begin)) > needToFill.get(S.charAt(begin))) {
if(needToFill.containsKey(S.charAt(begin))
&& hasFound.get(S.charAt(begin)) > needToFill.get(S.charAt(begin))){
hasFound.put(S.charAt(begin), hasFound.get(S.charAt(begin)) - 1);
}
begin++;
}
if(end - begin < minWinEnd - minWinBegin){
minWinEnd = end;
minWinBegin = begin;
}
}
}
}
return minWinBegin == -1 ? "" : S.substring(minWinBegin, minWinEnd + 1);

O(n)

这个算法的亮点是只用一个整型变量就判断了是否是一个合法window。

该算法教育我们:

1.做题要有画面感,而且是精确的画面感;

2.如果用了超过2个复杂数据结构,应该考虑是否有更简单的思路。;

3.人生是一场不停的战斗,不断优化你的算法。

LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]的更多相关文章

  1. LeetCode 笔记系列16.2 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]

    题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...

  2. LeetCode 笔记系列16.1 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]

    题目: Given a string S and a string T, find the minimum window in S which will contain all the charact ...

  3. LeetCode 76. 最小覆盖子串(Minimum Window Substring)

    题目描述 给定一个字符串 S 和一个字符串 T,请在 S 中找出包含 T 所有字母的最小子串. 示例: 输入: S = "ADOBECODEBANC", T = "ABC ...

  4. Minimum Window Substring @LeetCode

    不好做的一道题,发现String Algorithm可以出很多很难的题,特别是多指针,DP,数学推导的题.参考了许多资料: http://leetcode.com/2010/11/finding-mi ...

  5. LeetCode解题报告—— Minimum Window Substring && Largest Rectangle in Histogram

    1. Minimum Window Substring Given a string S and a string T, find the minimum window in S which will ...

  6. 【LeetCode】76. Minimum Window Substring

    Minimum Window Substring Given a string S and a string T, find the minimum window in S which will co ...

  7. 53. Minimum Window Substring

    Minimum Window Substring Given a string S and a string T, find the minimum window in S which will co ...

  8. leetcode76. Minimum Window Substring

    leetcode76. Minimum Window Substring 题意: 给定字符串S和字符串T,找到S中的最小窗口,其中将包含复杂度O(n)中T中的所有字符. 例如, S ="AD ...

  9. 刷题76. Minimum Window Substring

    一.题目说明 题目76. Minimum Window Substring,求字符串S中最小连续字符串,包括字符串T中的所有字符,复杂度要求是O(n).难度是Hard! 二.我的解答 先说我的思路: ...

随机推荐

  1. Node Redis 小试

    Redis 是一个高性能的 key-value 数据库,为了保证效率,数据都是缓存在内存中,在执行频繁而又复杂的数据库查询条件时,可以使用 Redis 缓存一份查询结果,以提升应用性能. 背景 如果一 ...

  2. 数据流图(DFD)画法

    数据流图(DFD)画法要求 一.数据流图(DFD) 1.数据流图的基本符号 数据流图由四种基本符号组成,见图5-4-1所示. 图5-4-1  数据流图的基本符号 例:图5-4-2是一个简单的数据流图, ...

  3. jenkins 下载插件失败处理办法

    jenkins 下载插件失败,提示: java.io.IOException: Downloaded file /app/jenkins_home/plugins/jacoco.jpi.tmp doe ...

  4. ubuntu更新出错--Could not get lock /var/lib/dpkg/lock

    ubuntu在vps上安装好后,通常第一个命令是更新系统软件.然而在运行的过程中,却出现这样的错误: E: Could not get lock /var/lib/dpkg/lock - open ( ...

  5. ubuntu下修改读写权限

    把home下所有文件所有者改成输入目标 $ chown - R [your name].users /home/

  6. Objective-C的内存管理(一)黄金法则的理解

    转自:http://blog.csdn.net/lonelyroamer/article/details/7666851 一.内存管理黄金法则: The basic rule to apple is ...

  7. 线程相关函数(6)-pthread_cond_wait(),pthread_cond_signal(), 条件变量

    pthread_cond_tpthread_cond_initpthread_cond_destroypthread_cond_waitpthread_cond_timedwaitpthread_co ...

  8. yii2 ContentDecorator 和 block 挂件

    在做网站的过程中,大部分的页面结构都是相似的.如都有相同的头部和底部.各个页面这样仅仅是中间的部分不同. Yii中的布局文件就是用来实现这样的功能.如: 布局文件:@app/views/layouts ...

  9. 0063 MyBatis入门示例

    MyBatis是一个"半自动化"的ORM框架,ORM即Object/Relation Mapping,对象关系映射,是面向对象编程语言跟关系型数据库的桥梁,将编程语言对Java实体 ...

  10. 设置open_cursors参数

    1.进入终端,输入命令:sqlplus /nolog 2.输入命令:conn /as sysdba 3.输入命令:alter system set open_cursors=1000 scope=me ...