Skip to content

Commit

Permalink
Find All Anagrams in a String
Browse files Browse the repository at this point in the history
  • Loading branch information
Pranjal authored Feb 27, 2017
1 parent 1a74ddc commit 2251478
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions FindAllAnagramsInAString.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
map<char, int> forP;

for(int i = 0; i < p.size(); i++){
if(forP.find(p[i]) == forP.end()){
forP[p[i]] = 1;
}
else{
forP[p[i]]++;
}
}

int start = 0, i = 0, n = s.size();

map<char, int> m;

vector<int> sol;

while(i < n){
if(m.find(s[i]) == m.end()){
m[s[i]] = 1;
}
else{
m[s[i]]++;
}

if((i - start) == p.size()){
if(m[s[start]] == 1){
m.erase(m.find(s[start]));
}
else{
m[s[start]]--;
}
start++;
}

if(m == forP){
sol.push_back(start);

}
i++;
}

return sol;
}
};

0 comments on commit 2251478

Please sign in to comment.