您的位置:首页 > 产品设计 > UI/UE

Leetcode:Repeated DNA Sequences

2015-02-12 01:10 295 查看
    开始看到题目,觉得就是直接从第一个子字符串开始遍历,并存储在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)
4000
;
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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息