76. 最小覆盖子串
为保证权益,题目请参考 76. 最小覆盖子串(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <string>
#include <unordered_map>
#include <climits>
using namespace std;
class Solution {
private:
unordered_map<char, int> smaps;
unordered_map<char, int> tmaps;
/**
*
* @return
*/
bool check() {
for (auto iter = tmaps.begin(); iter != tmaps.end(); iter++) {
if (!(smaps.find(iter->first) != smaps.end() && smaps.at(iter->first) >= tmaps.at(iter->first))) {
return false;
}
}
return true;
}
/**
* @brief initial
*/
void init(string &s, string &t) {
for (string::iterator iter = t.begin(); iter != t.end(); iter++) {
if (tmaps.find(*iter) != tmaps.end()) {
tmaps[*iter]++;
} else {
tmaps.insert(unordered_map<char, int>::value_type(*iter, 1));
}
}
}
public:
string minWindow(string s, string t) {
init(s, t);
int l = 0, r = 0;
string ans;
int curLen = INT_MAX;
while (l <= r) {
if (check()) {
if (r - l < curLen) {
ans = s.substr(l, r - l);
curLen = r - l ;
}
smaps[s[l]] --;
l++;
} else {
if(smaps.find(s[r]) != smaps.end()){
smaps[s[r]]++;
}else{
smaps.insert(unordered_map<char, int>::value_type(s[r], 1));
}
r++;
if(r > s.length()){
break;
}
}
}
return ans;
}
};
int main() {
Solution so;
cout << so.minWindow("ABCDEFA", "") << endl;
return 0;
}
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
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
Python
python
from collections import Counter
1