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).

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.

 

解题思路:

这道题我们可以用滑动窗口来解决。

首先我们先将t中的字符放到hashmap中,对应的是字符和它出现的次数。

然后我们遍历s,并用滑动窗口来寻找最短的子串。

首先向窗口里加入字符,即移动right。

在移动right的途中,遇见存在于t中的字符,对map中t的出现次数-1,并且当map[s[right]] > 0 时对总计数count+1。

当count与t.size()相等时,说明当前窗口[left, right]中包括了t中所有的字符,我们可以尝试移动left来去掉当前窗口中不属于t中的字符串,并且更新返回字符串ret。

若当前字符是t中的字符串,我们需要对m中该字符串出现的次数+1,若此时m[s[left]] > 0 说明移走了t中的字符串,当前窗口不包含t中所有字符,count需要-1。

再继续移动right

 

代码:

class Solution {
public:
    string minWindow(string s, string t) {
        if(t.size() > s.size())
            return "";
        unordered_map<char, int> m;
        for(char c : t){
            m[c]++;
        }
        int left = 0;
        int minLen = s.size()+1;
        int count = 0;
        string ret;
        for(int i = 0; i < s.size(); i++){
            if(m.count(s[i])){
                m[s[i]]--;
                if(m[s[i]] >= 0)
                    count++;
                while(count == t.size()){
                    if((i - left + 1) < minLen){
                        minLen = i - left + 1;
                        ret = s.substr(left, minLen);
                    }
                    if(m.count(s[left]) != 0){
                        m[s[left]]++;
                        if(m[s[left]] > 0)
                            count--;
                    }
                    left++;
                }
            }
        }
        return ret;
    }
};

 

posted @ 2018-06-13 06:47  妖域大都督  阅读(103)  评论(0编辑  收藏  举报