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

leetcode(187):Repeated DNA Sequences

2016-08-11 20:11 375 查看
原题:

All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: “ACGAATTCCG”. When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.

Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.

For example

Given s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”,

Return: [“AAAAACCCCC”, “CCCCCAAAAA”].

分析:题意为给定一个字符串,要求出现次数大于1的长度为10的子串集合。

思路是遍历一遍字符串,截取长度为10的子串,记录出现的次数,很容易想到map

Java实现如下:

public class Solution {
public List<String> findRepeatedDnaSequences(String s) {
List<String> ls = new ArrayList<String>();
if(s.length()==0 || s==null) return ls;
int len = s.length();
Map<String,Integer> map = new HashMap<String,Integer>();
for (int i = 0; i <= len-10; i++) {
String str = s.substring(i,i+10);
if(map.containsKey(str)){
map.put(str, map.get(str)+1);//重复出现的子串次数+1
}else{
map.put(str, 1);//新出现的子串加入map
}
}
for(Map.Entry<String, Integer> ent:map.entrySet()){
if(ent.getValue()>1) ls.add(ent.getKey());
}
return ls;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: