码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Repeated DNA Sequence"

时间:2015-02-09 09:19:39      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

Typical rolling-hash solution. That is, Boyer-Moore algorithm variation.

class Solution {
public:
    inline int encode(char c)
    {
        switch (c)
        {
        case A: return 0;
        case C: return 1;
        case G: return 2;
        case T: return 3;
        }
        return 0;
    }
    vector<string> findRepeatedDnaSequences(string s)
    {
        vector<string> ret;

        size_t len = s.length();
        if (len < 11) return ret;

        unordered_set<unsigned long> rec;
        unordered_set<string> rec_s;

        //    init
        unsigned long hash = 0;
        for (int i = 0; i < 10; i++)
        {
            hash *= 4;
            hash += encode(s[i]);
        }
        rec.insert(hash);

        //    go
        for (int i = 10; i < len; i++)
        {            
            hash *= 4;
            hash += encode(s[i]);
            hash &= (1 << 20) - 1;

            if (rec.find(hash) != rec.end())
            {
                string ts = s.substr(i - 9, 10);
                if (rec_s.find(ts) == rec_s.end())
                {
                    rec_s.insert(ts);
                    ret.push_back(ts);
                }
            }
            else
            {
                rec.insert(hash);
            }
        }

        return ret;
    }
};

LeetCode "Repeated DNA Sequence"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4280798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!