LC76 Minimum Window Substring

利用哈希表和滑动窗口来做题。一开始窗口内没有包含所有T的字符,扩大窗口直到包含T所有字符为止。然后再将窗口的左端向右移动,直到不能移动为止(再移动的话窗口内就没有所有T的字符了)。然后再移动窗口右端。如此循环。

 1 class Solution {
 2 public:
 3     string minWindow(string s, string t) {
 4         string str="";
 5         if(s==""||t==""||(s.size()<t.size()))
 6             return str;
 7         vector<int> expect(256,0);
 8         vector<int> real(256,0);
 9         for(int i=0;i<t.size();i++)
10             expect[t[i]]++;
11         int front=0;
12         int end=0;
13         int len=999999999;
14         int start=0;
15         for(;end<s.size();end++)
16         {
17             if(expect[s[end]]>0)
18             {
19                 real[s[end]]++;
20                 if(real[s[end]]<=expect[s[end]])
21                     count++;
22             }
23             if(count==t.size())
24             {
25                 while(expect[s[front]]==0||real[s[front]]>expect[s[front]])
26                 {
27                     real[s[front]]--;
28                     front++;
29                 }
30                 if(len>end-front+1)
31                 {
32                     len=end-front+1;
33                     start=front;
34                 }
35             }
36         }
37         return (999999999==len)?"":s.substr(start,len);
38     }
39 };
View Code

 

posted @ 2016-03-07 22:38  vaevaevae  阅读(184)  评论(0编辑  收藏  举报