https://leetcode.com/problems/find-all-anagrams-in-a-string/

1. Use STL sort():

  1. //TLE
  2. class Solution {
  3. public:
  4. vector<int> findAnagrams(string s, string p) {
  5. vector<int> result;
  6. if(p.length()>s.length())
  7. return result;
  8. string sub = "";
  9. int n = p.length();
  10. int i;
  11. int sum = 0;
  12. for(i = 0; i <= s.length() - n; i++){
  13. sub = s.substr(i, n);
  14. if(isAnagram(sub, p)){
  15. result.push_back(i);
  16. break;
  17. }
  18. }
  19. return result;
  20. }
  21. private:
  22. bool isAnagram(string sub, string p){
  23. sort(sub.begin(), sub.end());
  24. sort(p.begin(), p.end());
  25. return sub==p;
  26. }
  27. };
  28. //1. check is that possible s contains p
  29. //2. pick up count of letters in p
  30. //3. in s, pick substring with p.size() and consider is it an anagram of p
  31. //4. return the index if step 3 is true
  32. //5. return result

2. Use sliding the window:

  1. //32 ms 8.5 MB
  2. class Solution {
  3. public:
  4. vector<int> findAnagrams(string s, string p) {
  5. vector<int> result;
  6. if(p.length()>s.length())
  7. return result;
  8. vector<int> s_vec(26,0), p_vec(26,0);
  9. int i;
  10. for(i = 0; i < p.length(); i++){
  11. p_vec[p[i]-'a']++; //add count of letter p[i]
  12. s_vec[s[i]-'a']++; //add count of letter s[i]
  13. }
  14. if(p_vec==s_vec)
  15. result.push_back(0);
  16. for(; i < s.length(); i++){ //until the window reaches the end
  17. s_vec[s[i]-'a']++; //add count of letter s[i]
  18. s_vec[s[i-p.size()]-'a']--; //remove count of the previous head
  19. if(p_vec==s_vec)
  20. result.push_back(i-p.size()+1);
  21. }
  22. return result;
  23. }
  24. };