题目描述:
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"].Hash Table Bit Manipulation
解题思路:本题目中,最初采用的方法很简单,就是顺序取子串,存入hashmap中,如果已经存在说明超过两个,保存结果,否则,继续。但是使用这种方法得到的结果提交后出现,超时错误。其中,题目中提示采用位操作的形式,而此题目中只包含了A,C,G,T这四个字母,对应的值 分别为
65, 67, 71, 84,二进制表示为 1000001, 1000011, 1000111, 1010100,因此,我们可以只用后三位就可以表示这四个字母了,而且为了满足十个字符存储到一个里面,则需要int的30个位来存储即可,这样就可以大大的降低存储空间了,实现如下:
public List<String> findRepeatedDnaSequences(String s) {
List<String> result=new ArrayList<String>();
Map<Integer,Integer> r=new HashMap<Integer,Integer>();
int key=0;
for(int i=0;i<s.length();i++){
key=(key<<3|s.charAt(i)&0x7)&0x3fffffff;
if(r.containsKey(key)){
int k=r.get(key);
k++;
r.put(key, k);
if(k==2)result.add(s.substring(i-9,i+1));
}
else{
r.put(key, 1);
}
}
return result;
}