[leetcode] 187. Repeated DNA Sequences

<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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值