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;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018027202
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞