[C++] LeetCode 187. Repeated DNA Sequences

本文介绍了一种高效查找DNA分子中重复出现的10字母长序列的方法。通过将DNA的四种核苷酸转换为二进制表示,利用位运算来快速匹配重复序列。此算法避免了传统方法中的大量重复计算,显著提高了查找效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

解析

这道题最直观的解法可以使用map来做,但是用时会比较长。其次可以考虑用位运算。A,T,C,G分别用0,1,2,3表示,即使用2bit可以表示一个字符,那么10个长度的字符串只需要20bit即可。

代码

class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {
        unordered_map<char,int> m;
        m['A']=0,m['T']=1,m['C']=2,m['G']=3;
        unordered_map<int,int> count;
        int mask=0x3ffff,num=0;     //mask是用来取出低28位,方便右移
        vector<string> res;
        for(int i=0;i<9;i++){
            num=num<<2;
            num|=m[s[i]];
        }
        num=num<<2;
        for(int i=9;i<s.size();i++){
            num|=m[s[i]];
            count[num]+=1;
            if(count[num]==2){
                res.push_back(s.substr(i-9,10));    //如果一个num出现第二次则重复次数超过1,加入到res中,采用等号是防止重复加入
            }
            num=(mask&num)<<2;
        }
        return res;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值