[leetcode] 187. Repeated DNA Sequences

来源:互联网 发布:猫娘计划 知乎 编辑:程序博客网 时间:2024/06/04 19:57

<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">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.</span>

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

解法一:

这个思想与之前的不同,1)十个character的string用一个int表示。2)这个int是动态更新,不是完全替代。

首先,dna的string由ACGT表示,他们的ASCII码分别是:A: 0100 0001  C: 0100 0011  G: 0100 0111  T: 0101 0100

发现,他们最后三位是由不同的数字表示的。那么30位的bit就可以代表长度为10的string。在更新当前substr的时候,先用一个mask取int中最低的27位,然后左移3位,再把最新的char对应的3bit放到int的最低3位。查找重复substr使用hash table。

class Solution {public:    vector<string> findRepeatedDnaSequences(string s) {        vector<string> res;        if(s.size()<=10) return res;                int cur = 0, i =0;        int mask = 0x7ffffff;                while(i<9) cur = (cur<<3) | (s[i++] & 7);                unordered_map<int,int> m;        while(i<s.size()){            cur = ((cur&mask)<<3) | (s[i++] & 7);            if(m.find(cur)==m.end()){                m[cur]++;            }else{                if(m[cur]==1) res.push_back(s.substr(i-10,10));                m[cur]++;            }        }        return res;    }};


0 0
原创粉丝点击