关闭

leetcode Repeated DNA Sequence

标签: leetcode算法
81人阅读 评论(0) 收藏 举报

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"].

Show Company Tags
Show Tags

Have you met this question in a real interview? 

Yes
 

这道题思路是这样的:ACGT的ASCII码值后三位是不同的,分别为001 011 111 100 也就是说通过3bit可以表示一个基因,30bit可以表示一个10-letter-long的基因组,我们只需要将这个30bit的整数存入hashmap,然后每次判断新的整数是否存在于map中即可:

public List<String> findRepeatedDnaSequences(String s) {
    List<String> list=new ArrayList<>();
    Map<Integer,Integer> map=new HashMap<>();
    int gene=0;
    for(int i=0;i<s.length();i++){
        gene=(gene<<3|(s.charAt(i)&0x7))&(0x3fffffff);
        if(i<9) continue;
        if(map.get(gene)==null){
            map.put(gene,1);
        }
        else if(map.get(gene)==1){
            list.add(s.substring(i-9,i+1));
            map.put(gene,2);
        }

    }
    return list;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7931次
    • 积分:924
    • 等级:
    • 排名:千里之外
    • 原创:89篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条
    文章分类