leetcode No187. Repeated DNA Sequences

来源:互联网 发布:最终幻想猫女捏脸数据 编辑:程序博客网 时间:2024/05/01 10:37

Question:

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

Algorithm:


字符串中只包含4个字符:A, C, G, T。它们的ASCII码的二进制形式是:

  • A : 0100 0001
  • C : 0100 0011
  • G : 0100 0111
  • T : 0101 0100

这4个字符的末3位是不同的,因此,我们可以 3个bits 来表示其中的一个字符。
又因为每个子串的长度为10,因此总的位数是:10 x 3 = 30,一个int就足够存放它。

Accepted Code:

class Solution {public:/*    A:00 ->0    C:01 ->1    G:10 ->2    T:11 ->3*/    int encode(string str)  //    {        int res=0;        for(int i=0;i<str.size();i++)        {            res=res<<3|(str[i]&0x07);        }        return res;    }    vector<string> findRepeatedDnaSequences(string s) {        unordered_map<int,int> hash;        vector<string> res;        if(s.size()<10)            return res;        for(int i=0;(i+9)<s.size();i++)        {            if(hash[encode(s.substr(i,10))]==1)            {                res.push_back(s.substr(i,10));                hash[encode(s.substr(i,10))]++;            }            else               hash[encode(s.substr(i,10))]++;         }        return res;    }};





0 0