76. Minimum Window Substring

最小窗口字串

参考 https://www.cnblogs.com/grandyang/p/4340948.html

#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
class Solution {
    void print_dict(unordered_map<char,int>& letterCnt){
        for(auto it=letterCnt.begin();it!=letterCnt.end();++it){
            cout<<it->first<<" "<<it->second<<" ";
        }
        cout<<"\n";
    }
public:
    string minWindow(string s, string t) {
        string res="";
        unordered_map<char,int> letterCnt;
        int left=0,cnt=0,minLen=INT_MAX;
        for(auto a:t) {
            letterCnt[a]++;
        }
        for(int i=0;i<s.size();++i){
            printf("%d\n",cnt);
            print_dict(letterCnt);
            printf("%c\n",s[i]);
            if(--letterCnt[s[i]]>=0) cnt++;
            while(cnt==t.size()){

                if(i-left+1<minLen){
                    minLen=i-left+1;
                    res=s.substr(left,minLen);
                }

                if(++letterCnt[s[left]]>0){
                    cnt--;
                }
                left++;
            }
        }
        return res;
    }
};

int main(){
    Solution solution;
    std::cout<<solution.minWindow("ADBANC","ABC");
    return 0;
}

 可以用数组代替hashmap

//unordered_map<char,int> letterCnt;
vector letterCnt(256,0);

posted @ 2018-10-07 23:33  hopskin1  阅读(138)  评论(0编辑  收藏  举报