【Leetcode】Repeated DNA Sequences

题目链接: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)