Repeated DNA Sequences [leetcode]

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"].

暴力枚举肯定会超时,所以首先想到用哈希,以长为10子串作为key,出现次数作为value,如果value==1则加入到结果中。但内存消耗太大,还是不行。

稍微想了下便有了思路,压缩状态。 将长为10的字符串压缩为一个整数。

class Solution {
public:
int dna['T'+1];
char rdna[4] = {'A','C','G','T'};

vector<string> findRepeatedDnaSequences(string s){
	dna['A'] = 0; dna['C'] = 1; dna['G'] = 2; dna['T'] = 3;
	
	unordered_map<unsigned int,int> tab;
	vector<string> res;
	
	int len = s.length();
	
	for(int i=0;i<len-9;i++){
		unsigned int x = 0;
		for(int j=i+9;j>=i;j--){
			x += dna[s[j]]*pow(10,i+9-j);
		}
		if(tab[x]==1){
			//把x转换为字符串,加入res中
			string tps(10,' ');
			for(int j=9;j>=0;j--){
				tps[j] = rdna[x%10];
				x/=10;
			}
			res.push_back(tps);
		}
		tab[x]++;
	}
	
	return res;
}
};

再想了下,其实还可以再优化,因为每次将长为10的串转换为整数时不用从头算的,优化后的效率提高一倍

class Solution {
public:
int dna['T'+1];
char rdna[4] = {'A','C','G','T'};

vector<string> findRepeatedDnaSequences(string s){
	dna['A'] = 0; dna['C'] = 1; dna['G'] = 2; dna['T'] = 3;
	
	unordered_map<unsigned int,int> tab;
	vector<string> res;
	
	int len = s.length();
	if(len<=10) return res;
	
	unsigned int x = 0 ,k = 1000000000;
	for(int j=0;j<10;j++){ x += dna[s[j]]*k; k/=10;}
	tab[x] = 1;
	
	for(int i=1;i<len-9;i++){
		
		x -= dna[s[i-1]]*1000000000;
		x *=10; x += dna[s[i+9]];
		
		if(tab[x]==1){
			//把x转换为字符串,加入res中
			string tps(10,' ');
			unsigned int y = x;
			for(int j=9;j>=0;j--){
				tps[j] = rdna[y%10];
				y/=10;
			}
			res.push_back(tps);
		}
		tab[x]++;
	}
	
	return res;
}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值