@@ -34,7 +34,11 @@ using namespace std;
3434string minWindow (string S, string T) {
3535 string win;
3636 if (S.size ()<=0 || T.size ()<=0 || T.size () > S.size ()) return win;
37-
37+ /*
38+ * Declare two "hash map" for ASCII chars
39+ * f[]: represents the char found in string S
40+ * m[]: stores the chars in string T
41+ */
3842 const int MAX_CHARS = 256 ;
3943 int f[MAX_CHARS], m[MAX_CHARS];
4044
@@ -43,6 +47,10 @@ string minWindow(string S, string T) {
4347 memset (m, NOT_EXISTED, sizeof (m));
4448 memset (f, NOT_EXISTED, sizeof (f));
4549
50+ /*
51+ * Go through the T, and inital the m[] and f[]
52+ * Notes: a same char can be appeared multiple times.
53+ */
4654 for (int i=0 ; i<T.size (); i++) {
4755 m[T[i]]==NOT_EXISTED ? m[T[i]]=1 : m[T[i]]++ ;
4856 f[T[i]] = NOT_FOUND;
@@ -53,20 +61,28 @@ string minWindow(string S, string T) {
5361 int letterFound = 0 ;
5462 int begin = 0 ;
5563 for (int i=0 ; i<S.size (); i++) {
56-
64+ /* if S[i] is existed in T */
5765 if ( m[S[i]] != NOT_EXISTED ){
5866 char ch = S[i];
5967 f[ch]++;
68+
69+ /* if one char has been found enough times, then do not do letterFound++ */
6070 if (f[ch] <= m[ch]) {
6171 letterFound++;
6272 }
6373 if ( letterFound >= T.size () ) {
74+ /*
75+ * Find the beginning of the window
76+ * 1) f[S[begin]] == NOT_EXISTED ===> the char at the `begin` is not in T
77+ * 2) f[S[begin]] > m[S[begin]] ===> a same char appeared more than excepted.
78+ */
6479 while ( f[S[begin]] == NOT_EXISTED || f[S[begin]] > m[S[begin]] ) {
6580 if ( f[S[begin]] > m[S[begin]] ) {
6681 f[S[begin]]--;
6782 }
6883 begin++;
6984 }
85+ /* Calculate the minimized window size */
7086 if (winSize > i - begin + 1 ){
7187 start = begin;
7288 winSize = i - begin + 1 ;
0 commit comments