地址:https://leetcode.com/problems/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 ) O(n) O(n).
Example:
Input: S = “ADOBECODEBANC”, T = “ABC”
Output: “BANC”
Note:
- If there is no such window in S that covers all characters in T, return the empty string
""
. - If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
理解:
求S最短的子串,使得其包含T
实现:
使用滑动窗口的思想。
初始用一个map记录T出现的字符的次数。
若S的当前字符在T中,就从map中把计数减一。
counter大于0说明当前子串中没有完全包含T中的字符串。
需要注意的是,如果要缩小滑动窗的大小,只需要当子串已经不能包含T的时候,再修改counter即可。当map的value等于0的时候,此时加1大于0,就说明窗口已经不能包含T了。
最开始把counter初始化为T.size()也比较巧妙,其实到最后,counter最多也就是1。
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> map;
for (auto c : t)
map[c]++;
int counter = t.size(), l = 0, r = 0, d = INT_MAX, head = 0;
while (r < s.length()) {
char rc = s[r++];
if (map.count(rc)) {
if (map[rc]-- > 0)
counter--;
}
while (counter == 0) {
if (r - l < d) d = r - (head = l);
char lc = s[l++];
if (map.count(lc)) {
if (map[lc]++ == 0)
counter++;
}
}
}
return d == INT_MAX ? "" : s.substr(head, d);
}
};