C++ sliding window solution


  • 0
    A

    Thanks for the following solution. I just imitate it and give you the C++ solution.

    https://discuss.leetcode.com/topic/64434/shortest-concise-java-o-n-sliding-window-solution

    class Solution {
    public:
        vector<int> findAnagrams(string s, string p) {
            vector<int> m(26, 0), ans;
            for (char c : p)
                ++m[c - 'a'];
            
            int i = 0, j = 0, counter = p.length(); // j is last character index + 1
            while (j < s.length()) {
                if (m[s[j++] - 'a']-- > 0)
                    --counter;
                
                if (!counter)
                    ans.push_back(i);
                
                if (j - i == p.length() && m[s[i++] - 'a']++ >= 0)
                    ++counter;
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.