我使用下面的代码来实现一个函数,该函数可以查找字符串s中所有字符串p的字符串。Python collections.Counter效率
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
ans = list()
pcnt = collections.Counter(p)
for i in range(len(s)):
if collections.Counter(s[i:i+len(p)]) == pcnt:
ans.append(i)
return ans
大长度的输入字符串s运行时
,它给了我“时间超过限制”在网上的代码测试系统错误。但是,以下代码将不会发生此类问题:
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
ls, lp = len(s), len(p)
cp = collections.Counter(p)
cs = collections.Counter()
ans = []
for i in range(ls):
cs[s[i]] += 1
if i >= lp:
cs[s[i - lp]] -= 1
if cs[s[i - lp]] == 0:
del cs[s[i - lp]]
if cs == cp:
ans.append(i - lp + 1)
return ans
我知道为什么吗?看来这两个解决方案都使用两个len(p)最大大小的计数器?
第一个使用远比两个计数器多。它会在每个循环迭代中创建一个新的计数器,然后将其丢弃。不确定这是否是速度差异的原因,但它可能是。 – BrenBarn