LeetCode 题解工作台
重复的DNA序列
DNA序列 由一系列核苷酸组成,缩写为 'A' , 'C' , 'G' 和 'T' .。 例如, "ACGAATTCCG" 是一个 DNA序列 。 在研究 DNA 时,识别 DNA 中的重复序列非常有用。 给定一个表示 DNA序列 的字符串 s ,返回所有在 DNA 分子中出现不止一次的 长度为 1…
6
题型
8
代码语言
3
相关题
当前训练重点
中等 · 滑动窗口(状态滚动更新)
答案摘要
我们定义一个哈希表 ,用于存储所有长度为 的子字符串出现的次数。 遍历字符串 的所有长度为 的子字符串,对于当前子字符串 ,我们更新其在哈希表中对应的计数。如果 的计数为 ,我们就将它加入答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
DNA序列 由一系列核苷酸组成,缩写为 'A', 'C', 'G' 和 'T'.。
- 例如,
"ACGAATTCCG"是一个 DNA序列 。
在研究 DNA 时,识别 DNA 中的重复序列非常有用。
给定一个表示 DNA序列 的字符串 s ,返回所有在 DNA 分子中出现不止一次的 长度为 10 的序列(子字符串)。你可以按 任意顺序 返回答案。
示例 1:
输入:s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" 输出:["AAAAACCCCC","CCCCCAAAAA"]
示例 2:
输入:s = "AAAAAAAAAAAAA" 输出:["AAAAAAAAAA"]
提示:
0 <= s.length <= 105s[i]=='A'、'C'、'G'or'T'
解题思路
方法一:哈希表
我们定义一个哈希表 ,用于存储所有长度为 的子字符串出现的次数。
遍历字符串 的所有长度为 的子字符串,对于当前子字符串 ,我们更新其在哈希表中对应的计数。如果 的计数为 ,我们就将它加入答案。
遍历结束后,返回答案数组即可。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度。
class Solution:
def findRepeatedDnaSequences(self, s: str) -> List[str]:
cnt = Counter()
ans = []
for i in range(len(s) - 10 + 1):
t = s[i : i + 10]
cnt[t] += 1
if cnt[t] == 2:
ans.append(t)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They expect you to notice the substring length is fixed at 10, which strongly suggests a sliding window instead of variable-length scanning.
- question_mark
They want you to handle overlap correctly, because repeated DNA blocks can start one index apart and still count.
- question_mark
They may push for a bit manipulation upgrade after the hash-set solution, especially if they mention A, C, G, and T as a tiny alphabet.
常见陷阱
外企场景- error
Adding a sequence to the result every time it repeats, which produces duplicates when the same 10-letter block appears many times.
- error
Forgetting the early return when s.length < 10, which leads to unnecessary logic around impossible windows.
- error
Breaking the rolling encoding by not masking out old bits, causing the running state to represent more than 10 characters.
进阶变体
外企场景- arrow_right_alt
Return the count of each repeated 10-letter DNA sequence instead of only the unique repeated strings.
- arrow_right_alt
Change the target length from 10 to k, which keeps the same sliding-window idea but changes the mask width in the encoded version.
- arrow_right_alt
Process a stream of DNA characters online, where the last 10 characters define the current window and repeats are detected incrementally.