Minimum Window Substring

Given a string S and a string T, find the minimum window in S which will contain all the
characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the empty string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique
minimum window in S.

Solution: 1. Use two pointers: start and end.
First, move 'end'. After finding all the needed characters, move 'start'.
2. Use array as hashtable.

 1 class Solution {
 2 public:
 3     string minWindow(string S, string T) {
 4         int N = S.size(), M = T.size();
 5         if(N < M) return "";
 6         int need[256] = {0};
 7         int find[256] = {0};
 8         for(int i = 0; i < M; ++i)
 9             need[T[i]]++;
10 
11         int count = 0, resStart = -1, resEnd = N;
12         for(int start = 0, end = 0; end < N; ++end) {
13             if(need[S[end]] == 0)
14                 continue;
15             if(find[S[end]] < need[S[end]])
16                 count++;
17             find[S[end]]++;
18             if(count != M) continue;
19             // move 'start'
20             for(; start < end; ++start) {
21                 if (need[S[start]] == 0) continue;
22                 if (find[S[start]] <= need[S[start]]) break;
23                 find[S[start]]--;
24             }
25             // update result
26             if(end - start < resEnd - resStart) {
27                 resStart = start;
28                 resEnd = end;
29             }
30         }
31         return (resStart == -1) ? "" : S.substr(resStart, resEnd - resStart + 1);
32     }
33 };
原文地址:https://www.cnblogs.com/zhengjiankang/p/3676143.html