https://leetcode.com/problems/repeated-dna-sequences/
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"].
这道题可以把每个substring提出来,然后弄成一个hashtable,但这样的话浪费空间,而且对比两个string是否相同也是浪费时间的。
因此,可以看到A, C, G, T的最后3位都是不同的,因此只需要用最后3位代表这些字母就行了,这样长度为10的string就可以在一个int里面保存,并且,对比的时候,只需要对比int值是否相同就行了。
另外,长度为10的substring不需要每次都从头开始,因为前一个string的后9个是后一个string的前9个,所以只需要在int中把前一个string的第一个移走,把后一个string的最后一个移进来就行。
而且,不需要在统计完之后再解码,而是发现有重复substring的时候,直接把当前substring加进去就好,不然也要浪费解码的时间。
总之,这道题让我发现,很多工作都是不必要做的,一定要看出这些工作是不必要的,然后尽量节省时间。另外,这里的bit manipulation也很巧妙,应该多练习bit manipulation。
public class Solution {
public List<String> findRepeatedDnaSequences(String s) {
List<String> rst = new LinkedList<String>();
int mask = 0x3FFFFFFF;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
if(s.length()<=10) return rst;
int i=0;
int cur = 0;
while(i<9){
cur = (cur<<3) | (s.charAt(i++)&7);
}
while(i<s.length()){
cur = ((cur<<3) | (s.charAt(i++)&7)) & mask;
if(map.containsKey(cur)){
if(map.get(cur)==1){
map.put(cur, map.get(cur)+1);
rst.add(s.substring(i-10, i));
}
}
else{
map.put(cur, 1);
}
}
return rst;
}
}