Skip to content

Instantly share code, notes, and snippets.

@sourabh2k15
Created January 9, 2018 18:39
Show Gist options
  • Select an option

  • Save sourabh2k15/ffc561cb0b7b121478554a57ff3efdfb to your computer and use it in GitHub Desktop.

Select an option

Save sourabh2k15/ffc561cb0b7b121478554a57ff3efdfb to your computer and use it in GitHub Desktop.
Leetcode 438. Find All Anagrams in a String
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
unordered_map<char, int> table;
vector<int> ans;
for(char c : p){
table[c]++;
}
if(s.length() < p.length() || s.length() == 0) return ans;
int begin = 0, end = 0, word_size = p.length();
int counter = table.size();
while(end < s.length()){
char endchar = s[end];
if(table.count(endchar) == 1){
table[endchar]--;
if(table[endchar] == 0) counter--;
}
end++;
while(counter == 0){
if(end - begin == word_size) {
ans.push_back(begin);
}
char beginchar = s[begin];
if(table.count(beginchar) == 1){
table[beginchar]++;
if(table[beginchar] > 0) counter++;
}
begin++;
}
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment