From 9c39fd9898149da1f32d6e41e9a43523e06b6cf0 Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Sat, 30 Mar 2019 11:40:34 +0800 Subject: [PATCH] refactory the code to make it a bit readable --- .../minimumWindowSubstring.cpp | 91 ++++++++++--------- 1 file changed, 49 insertions(+), 42 deletions(-) diff --git a/algorithms/cpp/minimumWindowSubstring/minimumWindowSubstring.cpp b/algorithms/cpp/minimumWindowSubstring/minimumWindowSubstring.cpp index d0beb23..bd14543 100644 --- a/algorithms/cpp/minimumWindowSubstring/minimumWindowSubstring.cpp +++ b/algorithms/cpp/minimumWindowSubstring/minimumWindowSubstring.cpp @@ -31,75 +31,82 @@ using namespace std; #define INT_MAX 2147483647 -string minWindow(string S, string T) { +string minWindow(string s, string t) { string win; - if (S.size()<=0 || T.size()<=0 || T.size() > S.size()) return win; + if (s.size()<=0 || t.size()<=0 || t.size() > s.size()) return win; /* * Declare two "hash map" for ASCII chars - * f[]: represents the char found in string S - * m[]: stores the chars in string T + * window[]: represents the char found in string S + * dict[]: stores the chars in string T */ const int MAX_CHARS = 256; - int f[MAX_CHARS], m[MAX_CHARS]; - + int window[MAX_CHARS], dict[MAX_CHARS]; + const int NOT_EXISTED = -1; const int NOT_FOUND = 0; - memset(m, NOT_EXISTED, sizeof(m)); - memset(f, NOT_EXISTED, sizeof(f)); + memset(dict, NOT_EXISTED, sizeof(dict)); + memset(window, NOT_EXISTED, sizeof(window)); /* - * Go through the T, and inital the m[] and f[] + * Go through the T, and inital the dict[] and window[] * Notes: a same char can be appeared multiple times. */ - for(int i=0; i= T.size() ) { - /* - * Find the beginning of the window - * 1) f[S[begin]] == NOT_EXISTED ===> the char at the `begin` is not in T - * 2) f[S[begin]] > m[S[begin]] ===> a same char appeared more than excepted. - */ - while ( f[S[begin]] == NOT_EXISTED || f[S[begin]] > m[S[begin]] ) { - if ( f[S[begin]] > m[S[begin]] ) { - f[S[begin]]--; - } - begin++; + for(int right=0; right= t.size() ) { + /* + * Find the left of the window - try to make the window smaller + * 1) windows[S[left]] == NOT_EXISTED ===> the char at the `left` is not in T + * 2) window[S[left]] > dict[S[left]] ===> a same char appeared more than excepted. + */ + char chl = s[left]; + while ( window[chl] == NOT_EXISTED || window[chl] > dict[chl] ) { + if (dict[chl] != NOT_EXISTED ) { + //move the left of window + window[chl]--; + // reduce the number of letters found + if (window[chl] < dict[chl] ) letterFound--; } - /* Calculate the minimized window size */ - if(winSize > i - begin + 1){ - start = begin; - winSize = i - begin + 1; - } - + chl = s[++left]; } - + + /* Calculate the minimized window size */ + if(winSize > right - left + 1){ + start = left; + winSize = right - left + 1; + } + } } if (start>=0 && winSize>0) { - win = S.substr(start, winSize); + win = s.substr(start, winSize); } return win; } - int main(int argc, char**argv) { string S = "ADOBECODEBANC";