提交 c2e74442 编写于 作者: K KEQI HUANG 提交者: GitHub

Create 438._Find_All_Anagrams_in_a_String.md

上级 db3d1e16
### 438. Find All Anagrams in a String
题目:
<https://leetcode.com/problems/Find-All-Anagrams-in-a-String/>
难度:
Easy
思路
刚开始打算直接遍历整个s,时间复杂度为O(m*n),m和n分别为字符串p和s的长度,但是超时了
```python
python
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
l, res = len(p), []
for i in range(len(s)):
if collections.Counter(s[i:i+l]) == collections.Counter(p):
res.append(i)
return res
```
于是用双指针,left和right都从0开始往后遍历
```python
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
result = []
cnts = [0] * 26
for c in p:
cnts[ord(c) - ord('a')] += 1
left, right = 0, 0
while right < len(s):
cnts[ord(s[right]) - ord('a')] -= 1
while left <= right and cnts[ord(s[right]) - ord('a')] < 0:
cnts[ord(s[left]) - ord('a')] += 1
left += 1
if right - left + 1 == len(p):
result.append(left)
right += 1
return result
```
Author: Keqi Huang
If you like it, please spread your support
![Support](https://github.com/Lisanaaa/myTODOs/blob/master/WechatIMG17.jpeg)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册