我为 this 创建了一个解决方案leetcode 问题:
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
我的解决方案导致内存不足异常:
class Solution:
# @param {string} s
# @return {string[]}
def findRepeatedDnaSequences(self, s):
seen_so_far = set()
results = set()
for seq in self.window(10, s):
if seq in seen_so_far:
results.add(seq)
else:
seen_so_far.add(seq)
return list(results)
def window(self, window_size, array):
window_start = 0
window_end = window_size
while window_end < len(array):
yield array[window_start:window_end+1]
window_end += window_size
此解决方案有效:
class Solution:
# @param {string} s
# @return {string[]}
def findRepeatedDnaSequences(self, s):
d = {}
res = []
for i in range(len(s)):
key = s[i:i+10]
if key not in d:
d[key] = 1
else:
d[key] += 1
for e in d:
if d[e] > 1:
res.append(e)
return res
它们看起来本质上是一样的。我错过了什么?
最佳答案
您的 window
功能不正确。它产生一个子字符串序列 [0:11]
, [0:21]
, [0:31]
, ...(注意window_start
保持为零)。它可以被修复,例如作为
def window(self, window_size, array):
window_start = 0
while window_start < len(array) - window_size + 1:
yield array[window_start:window_start+window_size]
window_start += 1
编辑:子字符串结尾索引偏移 1。
关于algorithm - 为什么这段代码占用这么多内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109694/