LeetCode-Repeated DNA Sequences -解题报告

原题链接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"].

找出所有的长度为10的重复序列。


开始用map<string,int>直接映射超空间了,后来一想完全没必要吧每次的string都保存下来,就在想怎么将string hash成一个数,想到只有4个字母ACTG,长度为10,就想到用一个数组m[4][4][4][4][4][4][4][4][4][4],记录对应串的个数,后来又想到多为数组可以压缩成一维的,所以利用该原理将字符串压缩成一个数m['A']=0,m['T']=1,m['C']=2,m['G']=3,

Hash = Hash * 4 + m[str[i]]。 Hash < 4^10


在用map<int,int>就不会超空间了,当然用unordered_map<int, int> 会快一点点。


class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {
		unordered_map<int, int>Hash;
		vector<string>ans;
		int len = s.length();
		for (int i = 0; i <= len - 10; ++i)
		{
			string tmp = s.substr(i, 10);
			int cnt = ++Hash[MyHash(tmp)];
			if (cnt == 2)ans.push_back(tmp);
		}
		return ans;
	}
	int MyHash(string& str)
	{
		map<char, int>m;
		m['A'] = 0, m['T'] = 1, m['C'] = 2, m['G'] = 3;
		int HASH = 0;
		for (int i = 0; i < str.length(); ++i)
		{
			HASH = (HASH)* 4 + m[str[i]];
		}
		return HASH;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值