Skip to content

Commit c5e6cd1

Browse files
authored
Merge pull request larissalages#138 from PriyanshVerma/leetcode-cpp-all-anagrams-string
Find All Anagrams in a String
2 parents 5e5385e + 7d61e09 commit c5e6cd1

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

leetcode/cpp/string/438.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public:
3+
vector<int> findAnagrams(string s, string p) {
4+
if (s.length() < p.length()) {
5+
vector<int> v;
6+
return v;
7+
}
8+
9+
unordered_map<char,int> t , m ;
10+
for(char c : p) {
11+
t[c]++;
12+
}
13+
for(int i=0;i<p.length();i++){
14+
m[s[i]]++;
15+
}
16+
17+
vector<int> ans;
18+
int st=0, en=p.length()-1;
19+
while(en<s.length()) {
20+
if (same(m,t)) {
21+
ans.push_back(st);
22+
}
23+
acq(m, st, en, s);
24+
rel(m, st, en, s);
25+
}
26+
//
27+
return ans;
28+
}
29+
void acq(unordered_map<char,int> & m, int &st, int &en, string &str) {
30+
en++;
31+
if (en<str.length()) {
32+
m[str[en]]++;
33+
}
34+
}
35+
void rel(unordered_map<char,int> & m, int &st, int &en, string &str) {
36+
m[str[st]]--;
37+
if (m[str[st]]==0) m.erase(str[st]);
38+
st++;
39+
}
40+
bool same(unordered_map<char,int> & m, unordered_map<char,int> & t) {
41+
for(auto p : t) {
42+
if (m[p.first] != p.second)
43+
return false;
44+
}
45+
return true;
46+
}
47+
};

0 commit comments

Comments
 (0)