Repeated DNA Sequences

本文介绍了一种高效查找DNA中重复出现的10字母长序列的方法。利用ACGT四种核苷酸对应的ASCII值特性,通过位操作实现快速哈希,有效减少内存使用并加速查找过程。

注:这种方法是在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;
        
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值