Skip to content

Commit d2a711e

Browse files
Create Find All Anagrams in a String.cpp
1 parent 25f6820 commit d2a711e

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
2+
3+
class Solution {
4+
public:
5+
bool checkEqual(vector<int> &m1, vector<int> &m2) {
6+
for(int i = 0; i < 26; i++) {
7+
if(m1[i] != m2[i]) return false;
8+
}
9+
return true;
10+
}
11+
vector<int> findAnagrams(string s, string p) {
12+
vector<int> m1(26, 0), m2(26, 0);
13+
for(int i = 0; i < p.length(); i++) {
14+
m2[p[i] - 'a']++;
15+
}
16+
int i = 0;
17+
int j = 0;
18+
vector<int> ans;
19+
while(j < s.length()) {
20+
m1[s[j]-'a']++;
21+
if(j-i+1 < p.length()) {
22+
j++;
23+
}
24+
else if(j-i+1 == p.length()) {
25+
if(checkEqual(m1, m2)) ans.push_back(i);
26+
m1[s[i]-'a']--;
27+
i++;
28+
j++;
29+
}
30+
}
31+
return ans;
32+
}
33+
};

0 commit comments

Comments
 (0)