workday vo Minimum Window Substring

哈希表+遍历子串 On2超时

class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<char, int> map;
        for(char c : t){
            map[c] ++;
        }
        string ans = "";
        for(int i = 0; i < s.length(); i++){
            unordered_map<char, int> smap;
            int len = 0;
            for(int j = i; j < s.length(); j++){
                if(map.find(s[j]) != map.end() &&  smap[s[j]] < map[s[j]]){
                    smap[s[j]] ++;
                    len++;
                }
                if(len == t.length()){
                    if(ans == ""){
                        ans = s.substr(i, j-i+1);
                        //cout<<'a'<
                    }
                    else if(s.substr(i, j-i+1).length() < ans.length()){
                        ans = s.substr(i, j-i+1);
                        //cout<
                    }
                    break;
                }
            }
        }
        return ans;
    }
};

滑动窗口

class Solution {
public:
    string minWindow(string s, string t) {
        if(s.length() == 0 || t.length() == 0){
            return "";
        }
        
        unordered_map<char, int> tdict;
        for(int i = 0; i < t.length(); i++){
            tdict[t[i]]++;
        }
        
        int required = tdict.size();
        
        int l = 0, r = 0;
        
        int formed = 0;
        
        unordered_map<char, int> windowcount;
        
        
        string ans = "";
        while(r < s.length()){
            char c = s[r];
            windowcount[c]++;
            
            if(tdict.find(c) != tdict.end() && windowcount[c] == tdict[c]){
                formed++;
            }
            
            while(l <= r && formed == required){
                c = s[l];
                if(ans == "" || r-l+1 < ans.length()){
                    ans = s.substr(l, r-l+1);
                }
                
                windowcount[c]--;
                if(tdict.find(c) != tdict.end() && windowcount[c] < tdict[c]){
                    formed--;
                }
                
                l++;
            }
            r++;
            
        }
        return ans;
    }
};

你可能感兴趣的:(leetcode,leetcode,算法,职场和发展)