最小覆盖子串

157 阅读1分钟

image.png

链接:www.nowcoder.com/practice/c4…

思路:利用滑动窗口来做,使用一个l,r来确定子字符串,如果满足条件,就让l网右移,如果不满足,就让r右移

这一题自己做的时候感觉脑子有点僵化了,没啥想法,后来看到了双指针关键词,立马想出来了,但是代码的细节错了超级多,还是要活跃一点,自己一定可以的,加油,开心一点✌️

class Solution {
public:
    /**
     * 
     * @param S string字符串 
     * @param T string字符串 
     * @return string字符串
     */
    string minWindow(string S, string T) {
        // write code here
        string result;
        if(T.empty()||S.size()<T.size()) return result;

        unordered_map<char, int>Tcnt;
        int cnt1=0;
        for(int i=0;i<T.size();i++) {
            ++Tcnt[T[i]];
            if(Tcnt[T[i]]==1) ++cnt1;
        }

        unordered_map<char,int>Scnt;
        int cnt2=0,flag=0;
        result=S;

        int l=0,r=1;
        if(Tcnt.count(S[0])) {
            ++Scnt[S[0]];
            if(Scnt[S[0]]>=Tcnt[S[0]]) ++cnt2;
        }
        while(r<S.size()||cnt2>=cnt1) {
            cout<<l<<' '<<r<<' '<<cnt2<<endl;
            if(cnt2<cnt1) {
                //r右移
                if(Tcnt.count(S[r])) {
                    ++Scnt[S[r]];
                    if(Scnt[S[r]]==Tcnt[S[r]]) ++cnt2;
                }
                ++r;
            } else {
                //l右移
                flag=1;
                if(r-l<result.size()) result = S.substr(l,r-l);
                if(Tcnt.count(S[l])) {
                    --Scnt[S[l]];
                    if(Scnt[S[l]]<Tcnt[S[l]]) --cnt2; 
                }
                ++l;
            }
        }
        if(flag)
            return result;
        else 
            return "";

    }
};