https://leetcode.com/problems/find-all-anagrams-in-a-string/
1. Use STL sort():
//TLEclass Solution {public:vector<int> findAnagrams(string s, string p) {vector<int> result;if(p.length()>s.length())return result;string sub = "";int n = p.length();int i;int sum = 0;for(i = 0; i <= s.length() - n; i++){sub = s.substr(i, n);if(isAnagram(sub, p)){result.push_back(i);break;}}return result;}private:bool isAnagram(string sub, string p){sort(sub.begin(), sub.end());sort(p.begin(), p.end());return sub==p;}};//1. check is that possible s contains p//2. pick up count of letters in p//3. in s, pick substring with p.size() and consider is it an anagram of p//4. return the index if step 3 is true//5. return result
2. Use sliding the window:
//32 ms 8.5 MBclass Solution {public:vector<int> findAnagrams(string s, string p) {vector<int> result;if(p.length()>s.length())return result;vector<int> s_vec(26,0), p_vec(26,0);int i;for(i = 0; i < p.length(); i++){p_vec[p[i]-'a']++; //add count of letter p[i]s_vec[s[i]-'a']++; //add count of letter s[i]}if(p_vec==s_vec)result.push_back(0);for(; i < s.length(); i++){ //until the window reaches the ends_vec[s[i]-'a']++; //add count of letter s[i]s_vec[s[i-p.size()]-'a']--; //remove count of the previous headif(p_vec==s_vec)result.push_back(i-p.size()+1);}return result;}};
