jayati

Find All Anagrams in a String

Mar 24th, 2023
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> findAnagrams(string s, string p) {
  4.         vector<int> result;
  5.         if (s.length() < p.length()) {
  6.             return result;
  7.         }
  8.         vector<int> freqP(26);
  9.         for (char c : p) {
  10.             freqP[c - 'a']++;
  11.         }
  12.         vector<int> freqS(26);
  13.         for (int i = 0; i < p.length(); i++) {
  14.             freqS[s[i] - 'a']++;
  15.         }
  16.         if (freqP == freqS) {
  17.             result.push_back(0);
  18.         }
  19.         for (int i = 1; i <= s.length() - p.length(); i++) {
  20.             freqS[s[i - 1] - 'a']--;
  21.             freqS[s[i + p.length() - 1] - 'a']++;
  22.             if (freqP == freqS) {
  23.                 result.push_back(i);
  24.             }
  25.         }
  26.         return result;
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment