Repeated DNA Sequences

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"].
第一想法是暴力解决,但是考虑到只有四个字符,可以对字符编码,这样10个字符只需要一个整数的20位就可以表示出来。
class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {
        vector<string>  res;
        unordered_map<int, int> m;
        int ten = 0;
        int i = 0;
        while(i < 9){
            ten = ((ten<<2) | mapping(s[i++]));
        }

        while(i < s.size()){
            ten = ((ten<<2) & 0xfffff) | mapping(s[i]);
            //此处不能改为m[ten]++ >= 1,这样会在结果中出现重复的值
            if(m[ten]++ == 1){
                res.push_back(s.substr(i - 9,10));
            }
            i++;
        }
        return res;
    }
    int mapping(char c){
        if(c == 'A') return 0;
        if(c == 'C') return 1;
        if(c == 'G') return 2;
        if(c == 'T') return 3;
        else return -1;
    }
};

results matching ""

    No results matching ""