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 = len(s) - 10
cnt = Counter()
ans = []
for i in range(n + 1):
sub = s[i: i + 10]
cnt[sub] += 1
if cnt[sub] == 2:
ans.append(sub)
return ans
class Solution {
public List<String> findRepeatedDnaSequences(String s) {
int n = s.length() - 10;
Map<String, Integer> cnt = new HashMap<>();
List<String> ans = new ArrayList<>();
for (int i = 0; i <= n; ++i) {
String sub = s.substring(i, i + 10);
cnt.put(sub, cnt.getOrDefault(sub, 0) + 1);
if (cnt.get(sub) == 2) {
ans.add(sub);
}
}
return ans;
}
}
/**
* @param {string} s
* @return {string[]}
*/
var findRepeatedDnaSequences = function (s) {
const n = s.length - 10;
let cnt = new Map();
let ans = [];
for (let i = 0; i <= n; ++i) {
let sub = s.slice(i, i + 10);
cnt[sub] = (cnt[sub] || 0) + 1;
if (cnt[sub] == 2) {
ans.push(sub);
}
}
return ans;
};
func findRepeatedDnaSequences(s string) []string {
cnt := make(map[string]int)
n := len(s) - 10
ans := make([]string, 0)
for i := 0; i <= n; i++ {
sub := s[i : i+10]
cnt[sub]++
if cnt[sub] == 2 {
ans = append(ans, sub)
}
}
return ans
}
class Solution {
public:
vector<string> findRepeatedDnaSequences(string s) {
map<string, int> cnt;
int n = s.size() - 10;
vector<string> ans;
for (int i = 0; i <= n; ++i) {
string sub = s.substr(i, 10);
if (++cnt[sub] == 2) {
ans.push_back(sub);
}
}
return ans;
}
};