LeetCode 题解工作台

重复的DNA序列

DNA序列 由一系列核苷酸组成,缩写为 'A' , 'C' , 'G' 和 'T' .。 例如, "ACGAATTCCG" 是一个 DNA序列 。 在研究 DNA 时,识别 DNA 中的重复序列非常有用。 给定一个表示 DNA序列 的字符串 s ,返回所有在 DNA 分子中出现不止一次的 长度为 1…

category

6

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 滑动窗口(状态滚动更新)

bolt

答案摘要

我们定义一个哈希表 ,用于存储所有长度为 的子字符串出现的次数。 遍历字符串 的所有长度为 的子字符串,对于当前子字符串 ,我们更新其在哈希表中对应的计数。如果 的计数为 ,我们就将它加入答案。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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 <= 105
  • s[i]=='A''C''G' or 'T'
lightbulb

解题思路

方法一:哈希表

我们定义一个哈希表 cntcnt,用于存储所有长度为 1010 的子字符串出现的次数。

遍历字符串 ss 的所有长度为 1010 的子字符串,对于当前子字符串 tt,我们更新其在哈希表中对应的计数。如果 tt 的计数为 22,我们就将它加入答案。

遍历结束后,返回答案数组即可。

时间复杂度 O(n×10)O(n \times 10),空间复杂度 O(n×10)O(n \times 10)。其中 nn 是字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

重复的DNA序列题解:滑动窗口(状态滚动更新) | LeetCode #187 中等