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,
找出所有的长度为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;
}
};
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++实现JNI接口需要注意的事项
- c语言实现hashmap(转载)
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua教程(一):在C++中嵌入Lua脚本
- Ruby中Hash的11个问题解答
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- Ruby简明教程之数组和Hash介绍
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解