187. Repeated DNA Sequences Medium

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.

Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",

Return:
["AAAAACCCCC", "CCCCCAAAAA"].

思路:我们需要寻找的是重复出现过的子串,看到题目下方的提示 tags 说使用哈希表和位运算,因此我们想到使用数字来表示A,C,G,T,分别将他们标为0,1,2,3,我们可以用总共20位二进制数来表示长度为十的子串,并且用一个int来表示这个二进制数,这样只要两个子串有相同的int,我们就将其放在vector中作为结果输出,由于题目要求输出的子串中没有重复,所以我们使用map来排除重复的情况。

class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {
        map<string, string>result;
        if (s.length() <= 10) {
            return vector<string>();
        }
        int tran[s.length()];
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == 'A') {
                tran[i] = 0;
            }
            if (s[i] == 'C') {
                tran[i] = 1;
            }
            if (s[i] == 'G') {
                tran[i] = 3;
            }
            if (s[i] == 'T') {
                tran[i] = 2;
            }
        }
        map<int,int>hash;
        int sum = 0;
        int i = 0;
        while (i < 9) {
          sum = (sum << 2) | (tran[i]);
          i++;
        }
        for (; i < s.length(); i++) {
            sum = ((sum & 0x3ffff) << 2) | (tran[i]);
            map<int,int>::iterator it = hash.find(sum);
            if (it == hash.end()) {
                hash[sum] = 1;
            } else {
                result[s.substr(i - 9, 10)] = s.substr(i - 9, 10);
            }
        }
        vector<string>ans;
        map<string,string>::iterator it = result.begin();
        while (it != result.end()) {
            ans.push_back(it -> second);
            it++;
        }
        return ans;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值