Skip to content

Commit 5eb4cff

Browse files
committed
add python solution of 0438.
1 parent dbe68da commit 5eb4cff

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
## 找到字符串中所有字母异位词
2+
3+
### 问题描述
4+
5+
给定一个字符串 `s` 和一个非空字符串 `p`,找到 `s` 中所有是 `p` 的字母异位词的子串,返回这些子串的起始索引。
6+
7+
字符串只包含小写英文字母,并且字符串 `s``p` 的长度都不超过 20100。
8+
9+
**示例1:**
10+
```
11+
输入:
12+
s: "cbaebabacd" p: "abc"
13+
14+
输出:
15+
[0, 6]
16+
17+
解释:
18+
起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
19+
起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
20+
```
21+
**示例2:**
22+
```
23+
输入:
24+
s: "abab" p: "ab"
25+
26+
输出:
27+
[0, 1, 2]
28+
29+
解释:
30+
起始索引等于 0 的子串是 "ab", 它是 "ab" 的字母异位词。
31+
起始索引等于 1 的子串是 "ba", 它是 "ab" 的字母异位词。
32+
起始索引等于 2 的子串是 "ab", 它是 "ab" 的字母异位词。
33+
```
34+
**提示:**
35+
- 字母异位词指字母相同,但排列不同的字符串。
36+
- 不考虑答案输出的顺序。
37+
38+
### 解法
39+
`第0567`题。
40+
使用滑动窗口。窗口宽为`p`的长度,从左到右在`s`上滑动,若窗口内的字母出现频率和`p`中字母出现的频率一样,则此窗口的起始位置为一个起始索引。
41+
42+
```python
43+
class Solution:
44+
def findAnagrams(self, s, p):
45+
lens = len(s)
46+
lenp = len(p)
47+
if lens < lenp:
48+
return []
49+
flag1 = [0] * 26
50+
flag2 = [0] * 26
51+
for i, x in enumerate(p):
52+
flag1[ord(x) - 97] += 1
53+
ans = []
54+
for i, x in enumerate(s):
55+
flag2[ord(x) - 97] += 1
56+
if i >= lenp:
57+
flag2[ord(s[i - lenp]) - 97] -= 1
58+
if flag1 == flag2:
59+
ans.append(i - lenp + 1)
60+
return ans
61+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
def findAnagrams(self, s, p):
3+
"""
4+
:type s: str
5+
:type p: str
6+
:rtype: List[int]
7+
"""
8+
lens=len(s)
9+
lenp=len(p)
10+
if lens < lenp:
11+
return []
12+
flag1 = [0] * 26
13+
flag2 = [0] * 26
14+
for i, x in enumerate(p):
15+
flag1[ord(x) - 97] += 1
16+
ans = []
17+
for i, x in enumerate(s):
18+
flag2[ord(x)- 97] += 1
19+
if i >= lenp:
20+
flag2[ord(s[i - lenp]) - 97] -= 1
21+
if flag1 == flag2:
22+
ans.append(i-lenp+1)
23+
return ans

0 commit comments

Comments
 (0)