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:

1
2
3
4
5
6
7
8
9
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:

1
2
3
4
5
6
7
8
9
10
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".

思路

思路很简单,利用两个哈希表/26元素的数组,记录下s, p字母的统计数目,从而可以得出结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
res = []
pdict = {}
plen = len(p)
slen = len(s)
if(plen <= slen):
for i in range(plen):
if (pdict.has_key(p[i])):
pdict[p[i]] += 1
else:
pdict[p[i]] = 1
#print pdict
sdict = {}
for n in range(plen):
if (sdict.has_key(s[n])):
sdict[s[n]] += 1
else:
sdict[s[n]] = 1
print sdict
for m in range(slen-plen+1):
flag = 1
# 注意!在这个地方,"==","!="都是可以判断两个dict是否相等的操作符
# 如果遍历字典,反而会使时间复杂度大大提升,从而得到TLE,得不偿失。
if (sdict != pdict):
flag = 0
if (flag):
res.append(m)
if(m == slen-plen):
break
if (sdict.has_key(s[m]) and sdict[s[m]] != 1):
sdict[s[m]] -= 1
else:
del sdict[s[m]]
if (sdict.has_key(s[m+plen])):
sdict[s[m+plen]] += 1
else:
sdict[s[m+plen]] = 1
return res