[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; }};
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。