美文网首页
leetcode-2-重复的DNA序列

leetcode-2-重复的DNA序列

作者: foolgry | 来源:发表于2019-11-04 21:56 被阅读0次

    所有 DNA 都由一系列缩写为 A,C,G 和 T 的核苷酸组成,例如:“ACGAATTCCG”。在研究 DNA 时,识别 DNA 中的重复序列有时会对研究非常有帮助。

    编写一个函数来查找 DNA 分子中所有出现超过一次的 10 个字母长的序列(子串)。

    示例:

    输入:s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
    输出:["AAAAACCCCC", "CCCCCAAAAA"]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/repeated-dna-sequences
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    我这里用的是list,其实用set性能更好,list进行查询是O(logn),而set是O(1)的。

    public List<String> findRepeatedDnaSequences(String s) {
            int len = s.length();
            List<String> res = new ArrayList<String>();
            if (len <= 10) return res;
            Map<String, Integer> all = new HashMap<String, Integer>();
            for (int i = 0; i <= len - 10; i++) {
                String str = s.substring(i, i+10);
                if (all.containsKey(str)) {
                    all.put(str, all.get(str) + 1);
                } else {
                    all.put(str,1);
                }
            }
            for (Map.Entry<String, Integer> stringIntegerEntry : all.entrySet()) {
                if (stringIntegerEntry.getValue() > 1) {
                    res.add(stringIntegerEntry.getKey());
                }
            }
            return res;
        }
            ```

    相关文章

      网友评论

          本文标题:leetcode-2-重复的DNA序列

          本文链接:https://www.haomeiwen.com/subject/azdjbctx.html