187. Repeated DNA Sequences
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; } }