Skip to content

Instantly share code, notes, and snippets.

@yanhsiah
Created September 19, 2019 20:10
Show Gist options
  • Save yanhsiah/8b84f101788a1c53af1e1b4c87fdb319 to your computer and use it in GitHub Desktop.
Save yanhsiah/8b84f101788a1c53af1e1b4c87fdb319 to your computer and use it in GitHub Desktop.
string minWindow(string s, string t) {
vector<int> hash(128); // ASCII 0-127;
int match = 0, start = 0, end = 0;
int pos = start, len = INT_MAX; // return s.substr(pos, len);
for (char c : t) hash[c]++;
while (end < s.length()) {
// Means it's one of the char in t
if (hash[s[end]] > 0) { match++; }
// When end walks, minus every element by 1
hash[s[end]]--;
end++;
while (match == t.length()) {
if (end - start < len) {
len = end - start;
pos = start;
}
// Means it's one of the char in t (it's reduced to 0 when end pointer walks through).
if (hash[s[start]] == 0) { match--; }
// When start walks, plus every element by 1
hash[s[start]]++;
start++;
}
}
return len == INT_MAX ? "" : s.substr(pos, len);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment