LeetCode DNA重复序列

来源:互联网 发布:linux电子书下载 编辑:程序博客网 时间:2024/06/07 04:01

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来表示,例如,"ACGAATTCCG"。 我们学习DNA时,在DNA中识别重复序列有时很重要。

要求,写一个函数找到出现过多次,并且所包含10个英文字母的子序列。

//

分析,最直接的方法是,创建一个HashTable来记录所有的长度为10的子序列。

组后输出出现次数大于1的。

然而,没办法通过,leetcode, 报错原因是超过内存限制。

public List<String> findRepeatedDnaSequences(String s) {        List<String> list = new ArrayList<String>();        if(s == null || s.length() < 10) return list;                HashMap<String, Integer> table = new HashMap();        int L = 10;        for(int i = 0; i <= s.length() - L; i++){            String sub = s.substring(i, i + L);            if(table.containsKey(sub)){                table.put(sub, table.get(sub) + 1);            }else table.put(sub, 1);        }                Iterator<String> it = table.keySet().iterator();        while(it.hasNext()){            String key = it.next();            if(table.get(key) > 1)                list.add(key);        }        return list;    }

改进方案:

1. 第一输出List改用LinkedList而非ArrayList(原因在于两个List性质不同)。

2. HashMap中的Key是长度为string,也就是说,他所占有的内存大小约为2 * 10字节。继续分析发现所有字符串只包含四个不同的字符(A,C,G 和T),我们可以用2 bit来表示。这样自然会想到把string映射到一个整数空间,因为每个字符串可以唯一的用2*10 bit来表示。

3. HashMap中的值Value,也可以换成Boolean(只有1bit)。

一下是修改后的算法。


private int myHash(String s){        int n = 0;        for(int i = 0; i < s.length(); i++){                n <<=2;                char c = s.charAt(i);                if(c == 'C'){                    n += 1;                }else if(c == 'G'){                    n += 2;                }else if(c == 'T'){                    n += 3;                }        }        return n;    }        public List<String> findRepeatedDnaSequences(String s) {        List<String> list = new LinkedList<String>();        if(s == null || s.length() < 10) return list;        HashMap<Integer, Boolean> table = new HashMap<Integer, Boolean>();        int L = 10;        for(int i = 0; i <= s.length() - L; i++){            String sub = s.substring(i, i + L);            int hs = myHash(sub);            if(table.containsKey(hs)){                if(!table.get(hs)) list.add(sub);                table.put(hs, true);            }else{                table.put(hs, false);            }        }        return list;    }




0 0
原创粉丝点击