Question
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.
For example,
Given s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”,
Return:
[“AAAAACCCCC”, “CCCCCAAAAA”].
本题难度Medium。
集合法
【复杂度】
时间 O(N) 空间 O(N)
【思路】
利用集合set
存放遍历过1次的字符串,利用集合ans
存放遍历过2次的字符串。
【注意】
这里ans
使用集合而不用List的原因就在于去除重复。
【代码】
public class Solution {
public List<String> findRepeatedDnaSequences(String s) {
//require
Set<String> ans=new HashSet<>();
if(s==null||s.length()<10)return new LinkedList<String>(ans);
Set<String> set=new HashSet<>();
//invariant
for(int i=0;i+10<=s.length();i++){
String str=s.substring(i,i+10);
if(set.contains(str))ans.add(str);
else set.add(str);
}
//ensure
return new LinkedList<String>(ans);
}
}