码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Repeated DNA Sequences

时间:2016-05-27 12:51:15      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/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.

For example,

Given s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”,

Return:
[“AAAAACCCCC”, “CCCCCAAAAA”].

思路:
int是32位,ACTG可以用它们ascii码后三位区分,所以一个10个字符组成的子串只需要3*10=30位就能表示,遍历字符串所有长度为10的子串,将代表子串的int存入map中。

算法:

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

【Leetcode】Repeated DNA Sequences

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51483640

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!