Repeated DNA Sequences (LeetCode)

Question:

https://leetcode.com/problems/repeated-dna-sequences/

 

解答:

最开始的想法是对每一个10个字符的子串用hash table记录它们的出现次数。但是没通过OJ,应该是对于很长的字符串,子串的数目可能会很多,占用太多内存。所以用一个int代替子串。因为每个字符是A,C,G,T中的一个,所以2 bits就可以表示一个字符,一个子串需要20bits,所以int就足够了。

class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {
        std::unordered_map<int, int> count;
        vector<string> result;
        
        if (s.size() < 10)
            return result;
         
        int value = GetValue(s.substr(0, 10));
        count[value] = 1;

        for (int i = 10; i < s.size(); i++)
        {
            value &= 0x3FFFF; // remove bits 19,18
            value <<= 2;
            value += GetBitsValue(s[i]);

            if (count[value] == 1)
            {
                result.push_back(s.substr(i-9, 10));
            }
            
            count[value] ++;
        }
        
        return result;
    }
    
    int GetValue(const std::string& str)
    {
        int result = 0;
        for (int i = 0; i < str.size(); i++)
        {
            result <<= 2;
            result += GetBitsValue(str[i]);
        }
        
        return result;
    }
    
    int GetBitsValue(char c)
    {
        if (c == 'A')
            return 0;
        else if (c == 'C')
            return 1;
        else if (c == 'G')
            return 2;
        else
            return 3;
    }
};

 

posted @ 2015-03-12 13:57  smileheart  阅读(133)  评论(0)    收藏  举报