Leetcode:Repeated DNA Sequences

    开始看到题目,觉得就是直接从第一个子字符串开始遍历,并存储在List中,如果某个子字符串出现两次,就将其添加到结果列表中。结果TLE(Time Limited Exceeded)了。代码如下:

public class Solution {
    public List<String> findRepeatedDnaSequences(String s) {
        
        List<String> result=new ArrayList<String>();
        List<String> tempList=new ArrayList<String>();
        int size=s.length();
        String temp;
        if(size<10){
        	return null;
        }
        else{
        	for(int i=0;i<size-9;i++){
        		temp=s.substring(i, i+10);
        		if(tempList.contains(temp)&&!result.contains(temp)){
        			result.add(temp);
        		}
        		else{
        			tempList.add(temp);
        		}
        	}
        }
        return result;
    
    }
}
    想了很久不知道怎么改,果然是做题少了,思想很狭隘,然后看了网上的解法,说利用位操作来求解。具体可以参考http://www.cnblogs.com/hzhesi/p/4285793.html?utm_source=tuicoolhttp://www.cnblogs.com/grandyang/p/4284205.html。大概思想是把字符串映射为整数,对整数进行移位以及位与操作,以获取相应的子字符串。众所周知,位操作耗时较少,所以这种方法能节省运算时间。通过的代码如下:

public class Solution {
    public List<String> findRepeatedDnaSequences(String s) {
        
        Set<Integer> result=new HashSet<Integer>();
        List<String> result1=new ArrayList<String>();
        Set<Integer> tempList=new HashSet<Integer>();
        int size=s.length();
        String temp;
        if(size<10){
        	return result1;
        }
        else{
        	Map<Character, Integer> map = new HashMap<Character, Integer>();  
            map.put('A', 0);  
            map.put('C', 1);  
            map.put('G', 2);  
            map.put('T', 3); 
            int hash=0;
        	for(int i=0;i<size;i++){
        		if(i<9){
        			hash=(hash<<2)+map.get(s.charAt(i));
        		}
        		else{
        			hash=(hash<<2)+map.get(s.charAt(i));
        			hash&=(1<<20)-1;//整数占32个位,获取其低20位(题中要求是长度为10的子字符串,映射为整数后,子字符串总共占用20位)
        			if(tempList.contains(hash)&&!result.contains(hash)){
            			result1.add(s.substring(i-9,i+1));
            			result.add(hash);
            		}
            		else{
            			tempList.add(hash);
            		}
        		}
        		
        	}
        }
        return result1;
    
    }
}
    需要注意的是,当该字符串中没有出现长度为10的子字符串出现两次以上时,返回结果为“”,而不是null。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值