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'
.
class Solution:
def findRepeatedDnaSequences(self, s: str) -> List[str]:
n = 10
subs = set()
res = set()
for i in range(len(s) - n + 1):
sub = s[i:i + n]
if sub in subs:
res.add(sub)
subs.add(sub)
return list(res)
class Solution {
public List<String> findRepeatedDnaSequences(String s) {
int len = 10;
Set<String> subs = new HashSet<>();
Set<String> res = new HashSet<>();
for (int i = 0; i < s.length() - len + 1; ++i) {
String sub = s.substring(i, i + len);
if (subs.contains(sub)) {
res.add(sub);
}
subs.add(sub);
}
return new ArrayList<>(res);
}
}
/**
* @param {string} s
* @return {string[]}
*/
var findRepeatedDnaSequences = function(s) {
let n = 10;
let subs = new Set();
let res = new Set();
for (let i = 0; i < s.length - n + 1; i++) {
let sub = s.slice(i, i + n);
if (subs.has(sub)) {
res.add(sub);
}
subs.add(sub);
}
return [...res];
};