76. 最小覆盖子串

 1 class Solution 
 2 {
 3 public:
 4     string minWindow(string s, string t) 
 5     {
 6         unordered_map<char,int> hash;
 7         for(auto c : t) hash[c]++;
 8         int cnt = hash.size();
 9 
10         string res;
11         int c = 0;
12         for(int i = 0,j = 0;i < s.size();i ++)
13         {
14             if(hash[s[i]] == 1) c++;
15             hash[s[i]]--;
16             while(hash[s[j]] < 0) hash[s[j ++]] ++;
17             if(c == cnt)
18             {
19                 if(res.empty() || res.size() > i - j + 1) res = s.substr(j,i - j + 1);
20             }
21             cout << c << " ";
22         }
23         return res;
24     }
25 };

 

 1 string minWindow(string s, string t) {
 2     // 记录最短子串的开始位置和长度
 3     int start = 0, minLen = INT_MAX;
 4     int left = 0, right = 0;
 5 
 6     unordered_map<char, int> window;
 7     unordered_map<char, int> needs;
 8     for (char c : t) needs[c]++;
 9 
10     int match = 0;
11 
12     while (right < s.size()) {
13         char c1 = s[right];
14         if (needs.count(c1)) {
15             window[c1]++;
16             if (window[c1] == needs[c1]) 
17                 match++;
18         }
19         right++;
20 
21         while (match == needs.size()) {
22             if (right - left < minLen) {
23                 // 更新最小子串的位置和长度
24                 start = left;
25                 minLen = right - left;
26             }
27             char c2 = s[left];
28             if (needs.count(c2)) {
29                 window[c2]--;
30                 if (window[c2] < needs[c2])
31                     match--;
32             }
33             left++;
34         }
35     }
36     return minLen == INT_MAX ?
37                 "" : s.substr(start, minLen);
38 }

 

posted @ 2020-04-04 23:01  Jinxiaobo0509  阅读(185)  评论(0)    收藏  举报