187. Repeated DNA Sequences
Medium
358142FavoriteShare
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
Example:
Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" Output: ["AAAAACCCCC", "CCCCCAAAAA"]
class Solution {
public List<String> findRepeatedDnaSequences(String s) {
Set<String> seqSet = new HashSet<>();
Set<String> result = new HashSet<>();
for (int i = 0; i < s.length() - 9; i++) {
String seq = s.substring(i, i + 10);
if (seqSet.contains(seq)) {
result.add(seq);
}
seqSet.add(seq);
}
return new ArrayList<>(result);
}
}