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.
大意
答案
1 | class Solution { |
思路
求子串的问题一般都是哈希表和two piont 相结合.
先把t字符串读到哈希表中.
本题主要分两个阶段,刚开始初始左右指针都在s的起点处, 先不断的移动右指针,直到包含了所有的T字符,(用counter代表一共S中有了多少T里的字符,当counter等于T.size的时候,代表此时,左指针和右指针围住的子串符合题意了,这时进入第二个阶段,不断的移动左指针,去除掉一些左边不必要的指针,freq是每个字符在T中需要的个数,所以在第二个阶段,就是如果freq[s[l++]]++后,大于0,说明左指针和右指针已经围不住包含T的子串了,此时count–. count–后,会跳出第二个while循环,又会重新去移动右边的指针.
1 | 下面是用哈希表写 ,主要看上面那个解法把 |
Author: corn1ng
Link: https://corn1ng.github.io/2017/12/20/算法/leetcode76/
License: 知识共享署名-非商业性使用 4.0 国际许可协议