標籤: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