Day17-Find All Anagrams in a String(Medium)
问题描述:
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:
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".
解法:
python小知识一个counter是一个dict的子类,用于计数可哈希对象。
他其实就是一个dict,只不过平常我们对一个可以构造dict的对象,需要for循环遍历这个对象,而我们现在用这个容器一行代码就可以了。而这内部构造的时间复杂度还是O(n).
下面这两个代码都不是我原创的,是我看了一位大神的博客,算是默写下来了吧,总体用到的思想逻辑基本了然了,相关注释也写上了。总之就是用一个字典记录p中字符出现的次数,然后我们遍历
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
s_dict = collections.Counter()#先为S字符串设置一个空字典,用于后续添加字符出现次数的记录。
p_dict = collections.Counter(p)#为P初始化字典
result = []
for i in range(len(s)):
s_dict[s[i]] += 1#因为用的collections.Counter()初始化,所以即便是字典中原先没有的字符也可以这样加1.
if i >= len(p):##如果当前字符的位置超过了p字符串的长度,我们就从p这个长度的开始位置减去一位,相当于往后移动了一位
s_dict[s[i - len(p)]] -= 1
if s_dict[s[i - len(p)]] == 0:
del s_dict[s[i - len(p)]]
if s_dict == p_dict:
result.append(i - len(p) + 1)
return result