-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path76.cpp
96 lines (94 loc) · 2.62 KB
/
76.cpp
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// hashmap.cpp
class Solution {
bool allContain(unordered_map<char, int> &hash) {
for (auto p : hash)
if (p.second > 0)
return 0;
return 1;
}
public:
string minWindow(string s, string t) {
int l = 0, r = 0, minLen = 0x7fffffff, start;
unordered_map<char, int> hash;
for (char ch : t)
hash[ch]++;
unordered_map<char, int>::iterator it;
while (r < s.size() || allContain(hash)) {
while (r < s.size() && !allContain(hash))
if ((it = hash.find(s[r++])) != hash.end())
it->second--;
while (l < r && allContain(hash)) {
if (r - l < minLen) {
minLen = r - l;
start = l;
}
if ((it = hash.find(s[l++])) != hash.end())
it->second++;
}
}
return minLen == 0x7fffffff ? "" : s.substr(start, minLen);
}
};
// simple.cpp
class Solution2 {
bool allContain(vector<int> &arr) {
for (auto num : arr)
if (num > 0)
return 0;
return 1;
}
public:
string minWindow(string s, string t) {
int l = 0, r = 0, minLen = 0x7fffffff, start;
vector<int> hash(128);
for (char ch : t)
hash[ch]++;
while (r < s.size() || allContain(hash)) {
while (r < s.size() && !allContain(hash))
hash[s[r++]]--;
while (l < r && allContain(hash)) {
if (r - l < minLen) {
minLen = r - l;
start = l;
}
hash[s[l++]]++;
}
}
return minLen == 0x7fffffff ? "" : s.substr(start, minLen);
}
};
class Solution3 {
public:
string minWindow(string s, string t) {
unordered_map<char, int> tMap;
for (char c : t)
tMap[c]++;
int i = 0;
string res = s + ' ';
while(i < s.size() && tMap.find(s[i]) == tMap.end())
++i;
auto moveLeftWindUtilNotMatch = [&tMap, &s](int &i, const int j) {
for (;i <= j; ++i) {
if (auto it = tMap.find(s[i]); it != tMap.end()) {
if (++it->second > 0) {
++i;
break;
}
}
}
};
for (int j = i, matchCnt = 0; j < s.size(); ++j) {
if (tMap.find(s[j]) != tMap.end() && --tMap[s[j]] == 0) {
matchCnt++;
if (matchCnt == tMap.size()) {
moveLeftWindUtilNotMatch(i, j);
matchCnt--;
if (j - i + 2 < res.length()) {
res = s.substr(i - 1, j - i + 2);
}
}
}
}
return res.size() > s.size() ? "" : res;
}
};