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"].
解法1;
vector<string> findRepeatedDnaSequences(string s) {
vector<string> ans;
map<string,int> mp;
int n=s.size();
if(n<10) return ans;
int i;
for(i=10;i<=n;i++)
{
string str(s,i-10,10);
mp[str]++;
if(mp[str]==2)
ans.push_back(str);
}
return ans;
}
解法二;点击打开链接
上面只是单纯的使用hash的方法,没有考虑提示的bit操作。看了别人的代码。
用int代替string唯一的表示DNA序列,因为A = 0x41, C = 0x43, G =0x47, T = 0x54;也可以用二进制写成A,T,C,G各自的最后3位的二进制表示是不同的,对应1,3,7,4,因此可以用3位唯一的表示A, T,C,G中的一个,DNA序列可以用30个二进制位表示,它对应一个int内的整数。即一个string可以唯一的用一个int内的整数表示。
vector<string> findRepeatedDnaSequences(string s) {
unordered_map<int, int> m;
vector<string> r;
int t = 0, i = 0, ss = s.size();
while (i < 9)
t = t << 3 | s[i++] & 7;
while (i < ss)
if (m[t = t << 3 & 0x3FFFFFFF | s[i++] & 7]++ == 1)//当且仅当它出现2次的时候加入,避免超过2次的重复
r.push_back(s.substr(i - 10, 10));
return r;
}