[leetcode] 187 Repeated DNA Sequences,leetcoderepeated

來源:互聯網
上載者:User

[leetcode] 187 Repeated DNA Sequences,leetcoderepeated

(一)最一開始的做法是使用 map<string,int> 記錄每個10個字元的字串的個數,超過2就push_back進ans。但是MLE了,說明採用string並不是一個好方法。

下面是MLE的代碼:

class Solution {public:    vector<string> findRepeatedDnaSequences(string s) {    vector <string>  ans;        map<string,int> mp;        if(s.length()<10)        return ans;        for(int i=0;i<s.length()-10;i++)        mp[s.substr(i,10)]++;        map<string,int>::iterator it;        for(it=mp.begin();it!=mp.end();++it)        {        if(it->second>1)        ans.push_back(it->first);        }        return ans;    }};
(二)看了下Tags,提示要用位操作,讓我想到了霍夫曼編碼的首碼碼的唯一性,所以這裡可以採用如下標記:

A: 00  T:01 C:10 G:11一共10個字元,共20位,而一個int有32位,所以採用map<int,int> 的處理可以減少很多空間的佔用。

我們時鐘維護這樣一個20位的空間,遍曆的時候,先左移14位去掉第一個字元,然後右移12位在進行或操作添加新的尾部的字元,這樣又起到了節省時間的作用。

class Solution {public:    vector<string> findRepeatedDnaSequences(string s) {    vector <string>  ans;        map <int,int> mp;        map <char,int> cur;        set<string> st;        cur['A']=0;        cur['T']=1;        cur['C']=2;        cur['G']=3;        if(s.length()<10)        return ans;        int temp;        for(int i=0;i<9;i++)        {        temp<<=2;        temp|=cur[s[i]];         }       // mp[temp]++;        for(int i=9;i<s.length();i++)        {        temp<<=14;        temp>>=12;        temp|=cur[s[i]];        mp[temp]++;        if(mp[temp]>=2)        st.insert(s.substr(i-9,10));        }        set<string>::iterator it;        for(it=st.begin();it!=st.end();it++)        ans.push_back(*it);                return ans;    }};


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.