Repeated DNA Sequences

来源:互联网 发布:验证码js ajax demo 编辑:程序博客网 时间:2024/06/06 01:29

注:这种方法是在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"].

Subscribe to see which companies asked this question.

思路:

ACGT四个字母的ASCII值分别是65,67,71,84,暂且将四个字母的ASCII值设为x,所以(x-'A'+1)%5分别为1,3,2,0,也就是说每个字母只需要2bit就可以表示,20个bit就可以表示长度为10的字符串。

代码:

class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {
       vector<string> res;
       unordered_map<int,int> hash;
       int hashnum=0;
       int len=s.size();
       if (len<11)
       return res;
       for (int i=0; i<9; i++)
            hashnum=hashnum<<2|(s[i]-'A'+1)%5;
        for (int i=9;i<len; i++)
        {
            hashnum=(hashnum<<2|(s[i]-'A'+1)%5)&0xfffff;
            if (hash[hashnum]++==1)
                res.push_back(s.substr(i-9,10));
        }
        return res;
        
    }
};



原创粉丝点击