Leetcode Minimum Window Substring

题意:给出一个字符串,求出其子串中包含能组成给定字符串的最短子串。
思路:先用hash map判断是否包含。枚举以每个字母结尾的子串。用一个指针指向该子串的启示位置。
class Solution {
public:
    string minWindow(string s, string t) {
        string temps = "";
        map<char, int> testa;
        map<char, int> testb;
        for(int i = 0; i < s.length(); ++ i) testa[s[i]] ++;
        for(int i = 0; i < t.length(); ++ i) testb[t[i]] ++;
        if(!check(testa, testb)) return temps;
        
        map<char, int> myc;
        map<char, int> myhave;

        for(int i = 0; i < t.length(); ++ i) {
            myc[t[i]] ++;
        }
        vector<int> p(s.length(), -1);
        int st = 0;
        for(int i = 0; i < s.length(); ++ i) {
            //if(ch[s[i] - 'A'] == -2) continue;
            if(!myc[s[i]]) continue;
            myhave[s[i]] ++;
            if(check(myhave, myc)) {
                while(check(myhave, myc)) {
                    if(!myc[s[st]]) {
                        st ++;
                        continue;
                    }
                    myhave[s[st]] --;
                    p[i] = st;
                    st ++;
                }
            }
        }
        
        int shortest = INT_MAX;
        int r,l;
        r = l = 0;
        for(int i = 0; i < p.size(); ++ i) { //cout << p[i] << endl;
            if(p[i] != -1 && shortest > i - p[i] + 1) {
                shortest = i - p[i] + 1; 
                r = p[i];
                l = i;
            }
        }
        
        
        
        return s.substr(r, l - r + 1);
    }
    
    bool check(map<char, int> a, map<char, int> b) {
        std::map<char, int>::iterator it = b.begin();
        for(; it !=b.end(); it ++) {
            if(a[it->first] < it->second) return false;
        }
        return true;
    }
};
还有改进空间。

在空间上,可以只保留字串开始位置和长度。
在时间上,可以用一个计数器记录未满足要求的字母的个数。
class Solution {
public:
    string minWindow(string s, string t) {
        vector<int> m(128, 0);
        for(int i = 0; i < t.length(); ++ i) m[t[i]] ++;
        int c = t.length();
        int r,l; r = l = 0;
        int head = 0;
        int d = INT_MAX;
        for(int i = 0; i < s.length(); i ++) {
            if(m[s[i]] -- > 0) c --;
            //cout << c << endl;
            while(c == 0) {
                r = i; //cout << c << endl;
                if(d > r - l + 1) d = r - l + 1, head = l;
                if(m[s[l ++]] ++ == 0) c ++;
                
            }
        }
        //cout << head << endl;
        if(d == INT_MAX) return "";
        else return s.substr(head, d);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值