-
Notifications
You must be signed in to change notification settings - Fork 0
/
17 - Find All Anagrams in a String.cpp
39 lines (38 loc) · 1.07 KB
/
17 - 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
39
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res;
unordered_map <char , int> mp;
for(int i = 0; i<p.size(); i++){
mp[p[i]]++;
}
int counter = p.size();
int left = 0;
for(int i = 0; i<s.size(); i++){
if(mp.find(s[i]) != mp.end() && mp[s[i]]){
mp[s[i]]--;
counter--;
if(counter == 0){
res.push_back(left);
}
}
else{
while(left < i){
if(mp.find(s[left]) != mp.end()){
counter++;
mp[s[left]]++;
}
left++;
if(mp.find(s[i]) != mp.end() && mp[s[i]]){
i--;
break;
}
}
if(mp.find(s[left]) == mp.end()){
left = i + 1;
}
}
}
return res;
}
};