现在的位置: 首页 > 综合 > 正文

Minimum Window Substring

2018年04月08日 ⁄ 综合 ⁄ 共 613字 ⁄ 字号 评论关闭

尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符,头指针收缩头指针。得到窗口最小的情况

class Solution {
public:
    string minWindow(string S, string T) {
        int slen = S.size();
        int tlen = T.size();                //  record T[i]
        int need[256] = {0},has[256] = {0}, cnt = 0, ans = slen+1, mBegin, mEnd ;
        for(int i = 0; i < tlen; i++)
              ++need[T[i]];
        for(int begin = 0, end = 0; end < slen; end++){
          if(need[S[end]] == 0) continue;           //find T[i]
          ++has[S[end]];
          if(has[S[end]] <= need[S[end]])
            ++cnt;                                     //number of map
          if(cnt == tlen){
            while(need[S[begin]] == 0 || has[S[begin]]  > need[S[begin]]){
               if(has[S[begin]] > need[S[begin]])
                   --has[S[begin]];
                begin++;
            }
            int l = end - begin+1;
            if(l < ans){
               mBegin = begin;
               mEnd = end;
               ans = l;
            }
          }
        }
        return ans <= slen?S.substr(mBegin, mEnd- mBegin+1):"";
    }
};

【上篇】
【下篇】

抱歉!评论已关闭.