LeetCode 76. Minimum Window Substring

來源:互聯網
上載者:User

標籤:sub   多少   etc   color   min   star   視窗   har   start   

典型Sliding Window的問題,維護一個區間,當區間滿足要求則進行比較選擇較小的字串,重新修改start位置。

思路雖然不難,但是如何判斷當前區間是否包含所有t中的字元是一個痛點(t中字元有重複)。可以通過一個hashtable,記錄每個字元需要的數量,這個數量可以為負(當區間內字元數超過所需的數量)。還需要一個count判斷多少字元滿足要求了,如果等於t.size(),說明當前視窗的字串包含t裡所有的字元了。

class Solution {public:    string minWindow(string s, string t) {        unordered_map<char,int> hash; // char and the num it needs (it can be minus)        int start=0;        string res; int min_len=INT_MAX;        for (char ch:t) hash[ch]++;                    int count=0;        for (int end=0;end<s.size();++end){            if (hash.count(s[end])){                --hash[s[end]];                if (hash[s[end]]>=0) ++count;                while (count==t.size()){                    if (end-start+1<min_len){                        min_len = end-start+1;                        res = s.substr(start,end-start+1);                    }                    if (hash.count(s[start])){                        ++hash[s[start]];                        if (hash[s[start]]>0) --count;                    }                    ++start;                }            }        }        return res;    }};

 

LeetCode 76. 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.