187. Repeated DNA Sequences

50次阅读

共计 860 个字符,预计需要花费 3 分钟才能阅读完成。

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.
Example:
Input: s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”
Output: [“AAAAACCCCC”, “CCCCCAAAAA”]
难度:medium
题目:所有的DNA是由核甘酸简写字母A,C,G和T组成,例如:ACGAATTCCG。在研究DNA时重复序列有时是非常有用的。写函数找出所有由 10 个字母组成的且出现过 2 次及以上的子序列。
思路:hash map 统计子序列。
Runtime: 24 ms, faster than 71.23% of Java online submissions for Repeated DNA Sequences.
class Solution {
public List<String> findRepeatedDnaSequences(String s) {
Map<String, Integer> seqMap = new HashMap<>();
List<String> result = new ArrayList<>();
for (int i = 0; i < s.length() – 9; i++) {
String seq = s.substring(i, i + 10);
Integer count = seqMap.getOrDefault(seq, 0);
if (1 == count.intValue()) {
result.add(seq);
}
seqMap.put(seq, count + 1);
}

return result;
}
}

正文完
 0