我使用下面的代碼來實現一個函數,該函數可以查找字符串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