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

187. Repeated DNA Sequences

2016-03-22 10:28 447 查看
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"].


Subscribe to see which companies asked this question
关键在于把连着的5个字符用一个key表示,然后去查找有没有这样的一个key在hashmap中  

public class Solution {
public List<String> findRepeatedDnaSequences(String s) {  //关键在于把连着的5个字符用一个key表示,然后去查找有没有这样的一个key在hashmap中
List<String> ans = new ArrayList<String>();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int key = 0;
for (int i = 0; i < s.length(); i++) {
key = ((key << 3) | (s.charAt(i) & 0x7)) & 0x3fffffff;
if (i < 9) continue;
if (map.get(key) == null) {
map.put(key, 1);
} else if (map.get(key) == 1) {
ans.add(s.substring(i - 9, i + 1));
map.put(key, 2);
}
}
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: