leetcode[187]Repeated DNA Sequences

來源:互聯網
上載者:User

標籤:

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"].
class Solution {public:/** * 所有DNA都是由一系列堿基構成, 分別為ACGT, 題目要求找出所有長度為10的子串, 這些子串在原串中出現次數必須大於1次(重複出現) * 思路: *     1、暴力枚舉肯定是會逾時 *     2、hash *        1)unordered_set<string> repeated 儲存長度為10的子字串,遍曆字串,在repeated中尋找S[i]~S[i+9]構成的子串:
* 若未尋找到,則將其添加到repeated中,若找到,則重複,將其添加到vector<string> res中; * 2)然而unordered_set<string>對於超長的輸入串, 會消耗大量的儲存空間; * 改進:字串壓縮(10個字元char的子串需要8bit*10=80bit,而A C G T 四個字元需要兩位bit編碼00 01 10 11,10個char字元需要2bit*10=20bit,1 int=32 bit) * 3)另外還需要考慮res中的重複答案, 因為每次只要出現在repeated中就放入res, 這顯然會造成重複放置問題; * 改進:再構造一個unordered_set<int> check, 用於儲存已經存入res中的重複子串對應的strInt值; *
*/ vector<string> findRepeatedDnaSequences(string s) { vector<string> res; if(s.empty() || s.size()<10) return res; unordered_map<char, unsigned int> smap = {{‘A‘, 0},{‘C‘, 1},{‘G‘, 2},{‘T‘, 3}}; unordered_set<unsigned int> repeated, check; int strInt = 0; for(int i = 0; i < 10; i++){ strInt = (strInt<<2) + smap[s[i]]; } repeated.insert(strInt); for(int i = 10; i < s.size(); i++ ){ strInt = ((strInt & 0x3ffff)<<2)+smap[s[i]]; if(repeated.find(strInt)==repeated.end()){ repeated.insert(strInt); }else{ if(check.find(strInt) == check.end()){ res.push_back(s.substr(i-9,10)); check.insert(strInt); } } } return res; }};

 

leetcode[187]Repeated DNA Sequences

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.