Leetcode 438 Solution

This article provides solution to leetcode question 438 (find-all-anagrams-in-a-string)

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

Solution

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        vector<int> res;
        int m = s.length();
        int n = p.length();

        if (m < n || n == 0)
            return res;

        vector<int> a;
        vector<int> b;
        a.resize(26);
        b.resize(26);

        for (int i = 0; i < n; i++)
            b[p[i] - 'a']++;

        for (int i = 0; i < m; i++)
        {
            a[s[i] - 'a']++;

            if (i >= n)
            {
                a[s[i - n] - 'a']--;
            }

            if (a == b)
                res.push_back(i - n + 1);
        }

        return res;
    }
};