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