76. 最小覆蓋子串

ouyangxx發表於2024-11-11

思路:

活動視窗問題

反思:

1、考慮右指標已經移動到最右端,無法繼續移動的情況。(flag1的思路)
2、用map.empty()是要千萬注意:map[key]相當於往map中新增元素

程式碼:

class Solution {
public:
    unordered_map<char, int> mp;
    bool empty(){
        for(auto it = mp.begin(); it != mp.end(); it++){
            if(it -> second > 0) return false;
        }
        return true;
    }
    string minWindow(string s, string t) {
        vector<vector<int>> ans;
        int index[100005]={0};
        for(int i = 0; i < t.size(); i++){
            mp[t[i]]++;
        }
        int pre = -1, start = -1;
        for(int i = 0; i < s.size(); i++){
            if(mp[s[i]]){
                if(pre == -1) start = i;
                if(pre != -1) index[pre] = i;
                pre = i;
            }
        }
        if(start == -1){
            return "";
        }
        int l = start, r = start;
        bool flag1 = true; 
        while(l <= r){
            while(!empty() && flag1){
                mp[s[r]]--;
                if(index[r] == 0){
                    flag1 = false;
                    break;
                }
                if(!empty())r = index[r];
            }
            // cout<<l<<" "<<r<<" "<<mp['a']<<" "<<mp['e']<<" "<<mp['c']<<endl;
            if(empty()){
                ans.push_back({l, r});
                mp[s[l]]++; 
                if(index[l] == 0) break;
                l = index[l]; 
            }else{
                break;
            }
            if(!empty() && index[r] != 0){
                r = index[r];
            }
        }
        int minn = 100005, minl = -1 , minr = -1;
        for(int i = 0; i < ans.size(); i++){
            int rr = ans[i][1], ll = ans[i][0];
            if(rr - ll < minn){
                minn = rr - ll;
                minl = ll;
                minr = rr;
            }
        } 
        if(minl == -1){
            return "";
        }else{
            return s.substr(minl, minr - minl + 1);
        }
    }
};

相關文章