链接:https://leetcode.com/problems/minimum-window-substring/description/
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).
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.
思路:
思路:
维护两个索引Start 和 End(初值都为0),分别标识 子串W(这里表示Window)的开始位置和结束位置。
下面关键就是判断何时这两个索引要变化。
1.首先如果没有找到map中的单词,End++,继续往后找。
2.如果map中的字母还没找完,且找到了当前字母,则map中当前单词对应的value--(表示找到一个)。
3.当然可能有重复字母,即value减为负了,这样找出来的window包含多余重复字母肯定不是最优,所以我们要记录找到字母个数。
4.一旦找满单词,这个时候Start到End的位置肯定是包含目标T串所有字符的子串W(即Window)
5.但是这个window不是最优的,我们要对start++,排除不在map中的字符(其实就是让Start越过步骤1中跳过的字符),缩小window大小
6.还有需要优化的地方,就是当window中出现重复的字符,这时,map中该字符的value为负了,我们可以向前移动start。
关于第6点,比如说:
母串ABCDDDDDDDA
目标串ABC
那么当End移动到最后一个A时,Start只能停在第一个A处(为了保证Window中包含ABC三个字母)
而当End移动到最后一个A时,此时Window中多一个A(Map中A的值减为负了),这个时候Start就可以往前移动一下,做一步优化。
根据上述6点,代码就很容易了:
class Solution {
public:
std::string minWindow(std::string s, std::string t) {
if (s.empty() || t.empty() || s.length() < t.length()) {
return "";
}
unordered_map<char,int> map;
int count = t.length();
int start = 0, end = 0, minLen = INT_MAX, startIndex = 0;
/// UPVOTE !
for (char c : t) {
if(map.find(c) == map.end()) {
map[c]=1;
}
else {
map[c]++;
}
}
while (end < s.length()) {
if (map[s[end++]]-- > 0) {
count--;
}
while (count == 0) {
if (end - start < minLen) {
startIndex = start;
minLen = end - start;
}
if(map.count(s[start])) {
if (map[s[start++]]++ == 0) {
count++;
}
}
}
}
return minLen == INT_MAX ? "" : s.substr(startIndex, minLen);
}
};