[LeetCode] 187. Repeated DNA Sequences

The DNA sequence is composed of a series of nucleotides abbreviated as 'A''C''G', and 'T'.

  • For example, "ACGAATTCCG" is a DNA sequence.

When studying DNA, it is useful to identify repeated sequences within the DNA.

Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.

Example 1:

Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
Output: ["AAAAACCCCC","CCCCCAAAAA"]

Example 2:

Input: s = "AAAAAAAAAAAAA"
Output: ["AAAAAAAAAA"]

Constraints:

  • 1 <= s.length <= 105
  • s[i] is either 'A''C''G', or 'T'.

重复的DNA序列。

所有 DNA 都由一系列缩写为 'A','C','G' 和 'T' 的核苷酸组成,例如:"ACGAATTCCG"。在研究 DNA 时,识别 DNA 中的重复序列有时会对研究非常有帮助。

编写一个函数来找出所有目标子串,目标子串的长度为 10,且在 DNA 字符串 s 中出现次数超过一次。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/repeated-dna-sequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

给的 input 是一个 DNA 序列,请输出所有出现多次的 DNA 子序列。这题有位运算的做法但是个人觉得用 hashset 的做法更方便。

思路是用两个hashset,一个存子序列是否出现过(seen),另一个存最后的输出(res)。当某个子序列在seen中已经有了,就存入res;最后输出res里面所有的子序列。

时间O(n) - n是input字符串长度

空间O(n) - 用了两个hashset

Java实现

 1 class Solution {
 2     public List<String> findRepeatedDnaSequences(String s) {
 3         HashSet<String> seen = new HashSet<>();
 4         HashSet<String> res = new HashSet<>();
 5         for (int i = 0; i < s.length() - 9; i++) {
 6             String temp = s.substring(i, i + 10);
 7             if (!seen.add(temp)) {
 8                 res.add(temp);
 9             }
10         }
11         return new ArrayList<>(res);
12     }
13 }

JavaScript实现

 1 /**
 2  * @param {string} s
 3  * @return {string[]}
 4  */
 5 var findRepeatedDnaSequences = function(s) {
 6     let seen = new Set();
 7     let res = new Set();
 8     for (let i = 0; i < s.length - 9; i++) {
 9         const str = s.substring(i, i + 10);
10         if (seen.has(str)) {
11             res.add(str);
12         } else {
13             seen.add(str);
14         }
15     }
16     return Array.from(res);
17 };

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/11689679.html