18. Minimum Window Substring
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Example 2:
Input: s = "a", t = "a"
Output: "a"Solution: (Sliding Window + Hash Maps)
Last updated
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Example 2:
Input: s = "a", t = "a"
Output: "a"Last updated
class Solution
{
public:
string minWindow(string s, string t)
{
int minLen = INT_MAX;
unordered_map<char, int> tc;
unordered_map<char, int> sc;
string res = "";
for (int i = 0; i < t.length(); i++)
{
tc[t[i]]++;
}
int start = 0;
int i = 0;
int count = 0;
while (i < s.length())
{
if (tc.find(s[i]) != tc.end())
{
int val = tc[s[i]];
int sameVal = sc[s[i]];
if (sameVal < val)
{
count++;
}
sc[s[i]]++;
}
while (count >= t.length())
{
if (i - start + 1 < minLen)
{
res = s.substr(start, i - start + 1);
minLen = i - start + 1;
}
if (tc.find(s[start]) != tc.end())
{
int val = tc[s[start]];
int sameVal = sc[s[start]];
if (sameVal <= val)
{
count--;
}
sc[s[start]]--;
}
start++;
}
i++;
}
return res;
}
};