-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0438.cpp
More file actions
37 lines (35 loc) · 1.11 KB
/
Copy path0438.cpp
File metadata and controls
37 lines (35 loc) · 1.11 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
class Solution {
private:
map<char,int> buildExpectedMap(string const &p) {
map<char,int> m;
for (char c : p)
m[c]++;
return m;
}
map<char,int> buildComparisonMap(string const &s, string const &p) {
map<char,int> m;
for (int i = 0; i < p.length(); i++)
m[s[i]]++;
return m;
}
bool areMapsEqual(map<char,int> &m1, map<char,int> &m2) {
for (auto p : m1)
if (p.second != m2[p.first]) return false;
return true;
}
public:
vector<int> findAnagrams(string s, string p) {
if (p.length() > s.length()) return {};
vector<int> indices;
map<char,int> expected = buildExpectedMap(p);
map<char,int> current = buildComparisonMap(s, p);
if (areMapsEqual(expected, current)) indices.push_back(0);
for (int left = 0, right = p.length(); right < s.length(); left++, right++) {
current[s[left]]--;
current[s[right]]++;
if (areMapsEqual(expected, current))
indices.push_back(left+1);
}
return indices;
}
};