-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFindAllAnagramsinaString_438.cpp
52 lines (38 loc) · 1.1 KB
/
FindAllAnagramsinaString_438.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
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 438. Find All Anagrams in a String
~ Link : https://leetcode.com/problems/find-all-anagrams-in-a-string/
*/
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> idx;
int n = s.length(), k = p.length();
unordered_map<char, int> ump;
for (int i = 0; i < k; ++i) {
++ump[p[i]];
}
int cnt = ump.size();
int i = 0, j = 0;
while (j < n) {
if (ump.find(s[j]) != ump.end()) {
if (--ump[s[j]] == 0)
--cnt;
}
if ((j - i + 1) < k) {
++j;
}
else if ((j - i + 1) == k) {
if (cnt == 0)
idx.emplace_back(i);
if (ump.find(s[i]) != ump.end()) {
if (++ump[s[i]] == 1)
++cnt;
}
++i;
++j;
}
}
return idx;
}
};