**LeetCode 76. Minimum Window Substring

https://leetcode.com/problems/minimum-window-substring/


注意跟Leetcode 30的不同,由于这个题目,答案里面可以是有冗余所以

涉及到很多细节

答案可能是这样的,某一个字母出现的次数比t中该字母出现的次数多,所以在得到一个解时,再缩短解至最短

还可以做个优化,就hash数组代替map

#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <map>
#include <algorithm>

using namespace std;

class Solution {
public:
    string minWindow(string s, string t) {
        map <char, int> wd;
        for( int i=0; i<t.size(); i++ ) {
            wd[ t[i] ] ++;
        }

        map <char, int> check;
        for(int i=0;i<s.size();i++) {
            check[s[i]] ++;
        }
        int flag = 1;
        for(int i=0; i<t.size(); i++) {
            if(wd[t[i]] > check[ t[i] ]) {
                flag = 0;
                break;
            }
        }
        if( !flag ) return "";
        int st=0, en = st;
        int cnt = 0;
        string ret = s;
        //error case : no one right
        map<char, int> found;
        while(en < s.size()) {
            if( wd.find( s[en] ) != wd.end() ) {
                if( wd[ s[en] ] > found[ s[en] ] ) cnt ++;
                found[ s[en] ] ++;
                if(cnt == t.size()) {
                    int stop = 0;
                    while( !stop ) {
                        while( st <= en && wd.find( s[st] ) == wd.end() ) st++;
                        if(found[ s[st] ] > wd[ s[st] ]) {
                            found[ s[st] ] --;
                            st++;
                        } else {
                            stop=1;
                        }
                    }
                    if(en-st+1 < ret.size()) {
                        ret = s.substr(st, en-st+1);
                    }
                    cnt -- ;
                    found[ s[st] ] --;
                    st++;
                }
            }
            en ++;
        }
        return ret;
    }
};

int main() {
    freopen( "76", "r", stdin );
    string s,t;
    while( cin >> s >> t ) {
        Solution ss;
        cout << ss.minWindow(s, t) << endl;
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值