# 438. Find All Anagrams in a String

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

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

> 内容描述

```
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:

Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
```

## 解题方案

> 思路 1
******- 时间复杂度: O(m*n)******- 空间复杂度: O(1)******

刚开始打算直接遍历整个s，时间复杂度为O(m*n),m和n分别为字符串p和s的长度，但是超时了



```
class Solution(object):
    def findAnagrams(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """
        l, res = len(p), []
        maps = collections.Counter(p)
        for i in range(len(s)):
            if collections.Counter(s[i:i+l]) == maps:
                res.append(i)
        return res
```

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

于是用双指针，start 和 end 都从0开始往后遍历, beats 88.88%

```python
class Solution(object):
    def findAnagrams(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """
        res, start, end = [], 0, 0
        # maps = collections.Counter(p) # 这个贼慢
        maps = {}
        for c in p:
            maps[c] = maps.get(c, 0) + 1
        counter = len(maps)
        while end < len(s):
            if s[end] in maps:
                maps[s[end]] -= 1
                if maps[s[end]] == 0:
                    counter -= 1
            end += 1
            while counter == 0:
                if end-start == len(p):
                    res.append(start)
                if s[start] in maps:
                    maps[s[start]] += 1
                    if maps[s[start]] == 1:
                        counter += 1
                start += 1
        return res
```



