您的位置:首页 > 产品设计 > UI/UE

LeetCode-Repeated DNA Sequences -解题报告

2015-07-02 16:48 501 查看
原题链接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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode Hash