-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0076_MinimumWindowSubstring.cpp
More file actions
71 lines (57 loc) · 1.68 KB
/
Copy path0076_MinimumWindowSubstring.cpp
File metadata and controls
71 lines (57 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h>
using namespace std;
// Question Link : https://leetcode.com/problems/minimum-window-substring/
#include <iostream>
#include <unordered_map>
using namespace std;
class Solution
{
public:
string minWindow(string s, string t)
{
int s_length = s.length();
int t_length = t.length();
if (t_length > s_length)
{
return "";
}
unordered_map<char, int> count;
// Initialize count map for characters in string t
for (char c : t)
{
count[c]++;
}
int i = 0; // Left pointer of the window
int j = 0; // Right pointer of the window
int requiredChars = t_length; // Number of characters to match
int ansStart = -1; // Start index of the minimum window
int ansLength = INT_MAX; // Length of the minimum window
while (j < s_length)
{
if (count[s[j]] > 0)
{
// This character in s is required
requiredChars--;
}
count[s[j]]--;
j++;
while (requiredChars == 0)
{
// Update the minimum window
if (j - i < ansLength)
{
ansLength = j - i;
ansStart = i;
}
// Move the left pointer to the right
count[s[i]]++;
if (count[s[i]] > 0)
{
requiredChars++;
}
i++;
}
}
return (ansStart == -1) ? "" : s.substr(ansStart, ansLength);
}
};