forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind_All_Anagrams_in_a_String.cpp
38 lines (38 loc) · 1.04 KB
/
Find_All_Anagrams_in_a_String.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
class Solution {
bool isAnagram(unordered_map<char, int>& count, unordered_map<char, int>& freq) {
for(int i = 0; i <= 'z' - 'a'; ++i) {
if(freq[i] != count[i]) {
return false;
}
}
return true;
}
public:
vector<int> findAnagrams(string s, string p) {
int n = p.length();
int m = s.length();
vector<int> result;
if(n > m) {
return result;
}
unordered_map<char, int> freq;
for(int i = 0; i < n; ++i) {
freq[p[i] - 'a']++;
}
unordered_map<char, int> count;
for(int i = 0; i < n; ++i) {
count[s[i] - 'a']++;
}
if(isAnagram(count, freq)) {
result.push_back(0);
}
for(int left = 0, right = n; right < m; ++right) {
count[s[left++] - 'a']--;
count[s[right] - 'a']++;
if(isAnagram(count, freq)) {
result.push_back(left);
}
}
return result;
}
};