**LeetCode 76. Minimum Window Substring

来源:互联网 发布:黑金ps知乎 编辑:程序博客网 时间:2024/05/20 19:18

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
原创粉丝点击