This post shares a nice explanation, which is implemented here. The code is rewritten below.
1 class Solution { 2 public: 3 string minWindow(string s, string t) { 4 int m = s.length(), n = t.length(); 5 if (!m || !n) return ""; 6 int times[128] = {0}; 7 bool exist[128] = {false}; 8 for (int i = 0; i < n; i++) { 9 times[t[i]]++; 10 exist[t[i]] = true; 11 } 12 int l = 0, r = -1, idx = 0, len = INT_MAX; 13 while (l < m && r < m) { 14 if (n) { 15 times[s[++r]]--; 16 if (exist[s[r]] && times[s[r]] >= 0) n--; 17 } 18 else { 19 if (len > r - l + 1) { 20 len = r - l + 1; 21 idx = l; 22 } 23 times[s[l]]++; 24 if (exist[s[l]] && times[s[l]] > 0) n++; 25 l++; 26 } 27 } 28 return len == INT_MAX ? "" : s.substr(idx, len); 29 } 30 };