I'm posting an sliding window problem of LeetCode (Minimum Window Substring) with C++. If you have time and would like to review the code, please do so, I appreciate that.
On LeetCode, we are only allowed to change the variable names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).
Problem
Given a string
base_string
and a stringtarget
, find the minimum window inbase_string
which will contain all the characters intarget
in complexity O(n).Example:
Input:
base_string
= "ADOBECODEBANC",target
= "ABC" Output: "BANC" Note:If there is no such window in
base_string
that covers all characters intarget
, return the empty string "". If there is such window, you are guaranteed that there will always be only one unique minimum window inbase_string
.
C++
class Solution { public: string minWindow(string base_string, string target) { vector<int> count_map(128, 0); for (auto character : target) count_map[character]++; int left = 0, right = 0; int min_left = 0, min_right = INT_MAX; int target_length = target.size(); while (right < base_string.size()) { if (count_map[base_string[right++]]-- > 0) target_length--; while (target_length == 0) { if (right - left < min_right) min_right = right - (min_left = left); if (count_map[base_string[left++]]++ == 0) target_length++; } } return min_right == INT_MAX ? "" : base_string.substr(min_left, min_right); } };