187. Repeated DNA Sequences

本文介绍两种高效算法,用于找出DNA分子中所有重复出现的10字母长序列。第一种算法利用哈希表统计子串频率;第二种算法采用滑动窗口与位运算优化搜索过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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”]

代码一

class Solution {
    public List<String> findRepeatedDnaSequences(String s) {
        if(s == null || s.length() == 0) {
            return new ArrayList<String>();
        }

        Map<String, Integer> map = new HashMap<String, Integer>();

        for(int i = 0; i < s.length(); i++) {
            if(i + 10 > s.length()) {
                break;
            }
            String temp = s.substring(i, i + 10);
            if(map.containsKey(temp)) {
                map.put(temp, map.get(temp) + 1);
            }else {
                map.put(temp, 1);
            }
        }

        List<String> ans = new ArrayList<String>();
        for(Map.Entry<String, Integer> entry : map.entrySet()) {
            if(entry.getValue() > 1) {
                ans.add(new String(entry.getKey()));
            }
        }
        return ans;
    }
}

耗时75ms

代码二

class Solution {
    public List<String> findRepeatedDnaSequences(String s) {
        if(null == s || s.length() < 10) {
            return new ArrayList<String>();
        }

        List<String> ans = new ArrayList<String>();
        char[] map = new char[256];
        map['A'] = 0;//00
        map['T'] = 1;//01
        map['C'] = 2;//10
        map['G'] = 3;//11

        int hash = 0;
        int mask = 0xFFFFF;
        for(int i = 0; i < 10; i++) {
            hash = ((hash << 2 ) | map[s.charAt(i)] )  & mask;
        }

        BitSet seen = new BitSet(1 << 20); //因为10个字符的长度,每个字符我们用2位表示,因此一共需要20位
        BitSet more = new BitSet(1 << 20);

        seen.set(hash);

        int length = s.length();

        for(int i = 10; i < length; i++) {
            hash = ((hash << 2 ) | map[s.charAt(i)] )  & mask;
            if(seen.get(hash)) {
                if(!more.get(hash)) {
                    more.set(hash);
                    ans.add(s.substring(i - 9, i + 1));
                }

            } else {
                seen.set(hash);
            }
        }
        return ans;
    }
}

耗时9ms

代码二使用了滑动窗口加上位运算的方法,该方法的效率较高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值