题目:
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".
题意:
给定母串s和子串p,在s中找连续子串,其中子串中字符即为p中字符的无顺序组合,返回满足条件的所有子串的第一个字符的下标。
代码:
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
if s == '' :
return []
else :
result = [] #记录符合条件的子串的第一个字符的下标
dict1 = dict() #记录p中字符对应的字典
dict2 = dict() #记录s中的子串
for x in p :
if x not in dict1 : #python中并没有定义字典的未出现的key对应的value值为0,如果不先定义其为0,则报 key 未定义的错误
dict1[x] = 0
dict1[x] += 1
lenp = len(p)
lens = len(s)
for i in range(lens) :
if s[i] not in dict2 : #同样,对未出现过的key,都要先定义其对应的value为0
dict2[s[i]] = 0
dict2[s[i]] += 1 #每个遍历s的i,每次都将进来的s[i]对应的value增1,对应窗口的进口
if i >= lenp : #将窗口的出口减去一个,要减去的这个即为s[i-lenp]对应的value,这样始终保持窗口的长度是lenp
dict2[s[i-lenp]] -= 1
flag = 0
for x in dict1 : #判断两个字典是否相等,由于python中直接查找没定义的key对应的value,会报错,故每次都要判断key是否已在字典中
if x in dict2 :
if dict1[x] != dict2[x] :
flag = 1 #flag=1,两个字典不相等
else :
flag = 1
if flag == 0 :
result.append(i-lenp+1) #记录满足条件的字符串的首字符对应的下标
return result
笔记:
1、由于查找的子串顺序与p不一样都可以,故用字典的结构来解决顺序的问题
2、在s中找符合要求的子串的时候,使用了窗口的概念,窗口的长度最大为p的长度,s中每进来一个字符,就检查一遍窗口和目标字典,如果相同,则符合要求,否则,不符合要求。
3、python中直接查找没定义的key对应的value,会报错,故每次都要判断key是否已在字典中,才能对该key对应的value进行操作