LeetCode-Minimum Window Substring-最小視窗子串-滑動視窗演算法(尺取法)

來源:互聯網
上載者:User

標籤:blog   http   io   使用   ar   for   div   c   on   

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

線性複雜度的限制下,考慮使用滑動視窗法。這個方法的思路就是維持一個視窗,視窗向右邊界擴張以滿足限制條件。視窗左邊界收縮以盡量使其最小。

注意這個題目可能是一個典型的滑動視窗方法的實現。外部迴圈移動左邊界i,迴圈內部擴張右邊界p以滿足限制條件。並且內外都有終止可能。

使用兩個map和一個計數變數以快速統計條件限制的滿足情況。

class Solution {public:int n,m;string minWindow(string S, string T) {map <char,int> cm;map <char,int> stat;n=S.length();m=T.length();for (int i=0;i<m;i++){if (cm.find(T[i])==cm.end()){cm[T[i]]=1;}else{cm[T[i]]++;}stat[T[i]]=0;}int res=numeric_limits<int>::max();typedef pair <int,int> scpair;scpair minw;int q=0;int count=0;for (int i=0;i<n;i++){bool endFlag=false;while(count<m){q++;if (q>n){endFlag=true;break;}if (cm.find(S[q-1])==cm.end()){continue;}if (stat[S[q-1]]<cm[S[q-1]]){count++;}stat[S[q-1]]++;}if (endFlag){break;}if (res > q-i){res=q-i;minw=scpair(i,q);    }if (cm.find(S[i])==cm.end()){continue;}stat[S[i]]--;if (stat[S[i]]<cm[S[i]]){count--;}}if (res>n){return "";}//no winreturn S.substr(minw.first,minw.second-minw.first);}};

  

LeetCode-Minimum Window Substring-最小視窗子串-滑動視窗演算法(尺取法)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.