-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path438.cc
58 lines (47 loc) · 979 Bytes
/
438.cc
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
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
private:
using CharMap = std::unordered_map<char, int>;
bool is_equal(CharMap o, CharMap m) {
for (auto it = o.begin(); it != o.end(); ++it) {
if (m[it->first] != it->second) {
return false;
}
}
return true;
}
public:
vector<int> findAnagrams(string s, string p) {
if (s.size() < p.size()) {
return {};
}
CharMap o;
CharMap m;
std::vector<int> res;
for (int i = 0; i < p.size(); i++) {
o[p[i]]++;
m[s[i]]++;
}
int l = 0, r = p.size() - 1;
while (r < s.size()) {
if (is_equal(o, m)) {
res.push_back(l);
}
m[s[l++]]--;
m[s[++r]]++;
}
return res;
}
};
int main() {
Solution s;
std::string str = "cbaebabacd";
std::string p = "abc";
auto res = s.findAnagrams(str, p);
str = "abab";
p = "ab";
res = s.findAnagrams(str, p);
}