首页 > 其他 > 详细

LeetCode "Repeated DNA Sequence"

时间:2015-02-09 09:19:14      阅读:297      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!