Likou Selected Top Interview Questions---------Minimal Coverage Substring

Insert picture description here

Topic link

Idea: This
question should be studied well. The algorithm used is the sliding window. First, we must first understand the meaning of the question and turn it into our code. That is, the elements in the window must contain the given t string (including repetitions). Letters). After reading the meaning of the question, you can start reading the code.

Code:

class Solution {
    
    
public:
    string minWindow(string s, string t) {
    
    
        int left = 0, right = 0, start = 0, minLen = INT_MAX;
        unordered_map<char, int> need;  //这里用到了两个map容器作为窗口以及记录元素的个数
        unordered_map<char, int> window;
        for (char c : t) {
    
    
            need[c]++; // 目标字符数
        }
        int match = 0;
        while (1) {
    
     // 滑窗开始
          //  cout<<match<<'*'<<endl;
            if(right>=s.size() && match!=need.size()) break;
            while(right<s.size() && match!=need.size()){
    
      //先把窗口内的元素达到t的条件
                if(need.count(s[right])){
    
    
                    window[s[right]]++;
                    if(window[s[right]]==need[s[right]]) ++match;
                }
                ++right;
            }
           // cout<<left<<' '<<right<<endl;
            if(match==need.size() && minLen>right-left){
    
    
                minLen = right - left;
                start = left;
            }
            if(need.count(s[left])){
    
      //这里说,如果左边的事属于t内的元素才去管,否则就可以无视其他无用的元素
                window[s[left]] --;
                if(window[s[left]]<need[s[left]]) --match;
            }
            ++left;
        }
        return minLen == INT_MAX ? "" : s.substr(start, minLen);
    }
};

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/114028322