[leetcode] 187 Repeated DNA Sequences

(一)最一开始的做法是使用 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位的空间,遍历的时候,先左移2位,或上新的字符,这时共22位,我们再进行temp&=~(0x300000)去掉首位一个字符即可。

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=0;
        for(int i=0;i<10;i++)
        {
        	temp<<=2;
        	temp|=cur[s[i]]; 
        }
        mp[temp]++;
        for(int i=10;i<s.length();i++)
        {
        	temp<<=2;
        	temp&=~(0x300000);
        	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;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值