Middle-题目96:187. Repeated DNA Sequences

来源:互联网 发布:中国人工智能协会 编辑:程序博客网 时间:2024/05/19 12:17

题目原文:
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.
For example,
Given s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”,
Return:
[“AAAAACCCCC”, “CCCCCAAAAA”].
题目大意:
给出一个DNA序列(由’A’,’C’,’G’,’T’组成的字符串),求其中所有的在该DNA序列中出现至少两次的10位子序列。
题目分析:
方法一:(朴素解法,基于哈希表)构建一个HashMap,其中Key是原序列的所有的10位子序列(空间复杂度O(n)),value是这个序列的出现次数。如果发现某个key出现次数为2则加入列表(超过2则跳过,否则列表会出现重复串)
方法二:(基于Bit manipulation,来自discuss中大神的算法)分别把’A’,’C’,’G’,’T’编码为00,01,10,11.先计算前9个字符的编码,然后从第10个字符开始,去掉最高位的编码(与0xfffff求与),再加上最后一位的编码,放入集合中,如果集合重复了,则加入最终返回的列表。
源码:(language:java)
方法一:

public class Solution {    public List<String> findRepeatedDnaSequences(String s) {        List<String> list = new ArrayList<String>();        HashMap<String, Integer> dict = new HashMap<String, Integer>();        for(int i = 0;i<=s.length()-10;i++) {            String substr = s.substring(i,i+10);            if(!dict.containsKey(substr)) {                dict.put(substr, 1);            }            else {                int value = dict.get(substr) + 1;                if(value>2)                    continue;                dict.put(substr, value);                if(value == 2)                    list.add(substr);            }        }        return list;    }}

方法二:

public class Solution {    public List<String> findRepeatedDnaSequences(String DNA) {        ArrayList<String> res = new ArrayList<String>();        if(DNA.length()<10)    return res;        HashSet<Integer> once = new HashSet<Integer>();        HashSet<Integer> twice = new HashSet<Integer>();        int[] map = new int[26];        map['A'-'A'] = 0;        map['C'-'A'] = 1;        map['G'-'A'] = 2;        map['T'-'A'] = 3;        int enc = 0;        for(int i=0; i<9; ++i){            enc <<=2;            enc |= map[DNA.charAt(i)-'A'];        }        for(int j=9; j<DNA.length(); ++j){            enc <<=2;            enc &= 0xfffff;            enc |= map[DNA.charAt(j)-'A'];            if(!once.add(enc) && twice.add(enc))                res.add(DNA.substring(j-9,j+1));        }        return res;    }}

成绩:
方法一:40ms,beats 67.09%,众数38ms,5.66%
方法二:32ms,beats 95.90%
cmershen的碎碎念:
第二种方法有两个巧妙的处理方法是值得学习的:一是enc &= 0xfffff;表示去掉原字符串最高位编码,二是if(!once.add(enc) && twice.add(enc))代表这个编码第二次出现(虽然这个我还不太理解)

0 0
原创粉丝点击