All DNA are composed of a series of nucleotides abbreviated as a, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it's 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"].
The general idea is very simple, with a hashmap to store the corresponding 10 length of the DNA string and the number of occurrences, and finally the number of occurrences more than once in the list, here is the main problem is the map key if the direct string, there will be exceed time limit problem, The DNA string must be hashed into an int type integer,a->00; c->01; g->10; t->11; such a 10-character-length DNA sequence is mapped into a 20-bit 2-digit number, which can be used as a key for the 2 decimal number. The code is as follows:
Public classSolution {//converts a character to a corresponding 2-bit 2 binary number Public intToInt (Charc) {if(c== ' A ')return0; if(c== ' C ')return1; if(c== ' G ')return2; Else return3; } //convert Hashcode to DNA sequence PublicString ToString (intN) {stringbuffer sb=NewStringBuffer (); for(inti=0;i<10;i++) { Charc = ' T '; inttemp = n%4; N= N>>2; if(temp==0) c = ' A '; if(temp==1) c = ' C '; if(temp==2) c = ' G '; Sb.insert (0, c); } returnsb.tostring (); } PublicList<string>findrepeateddnasequences (String s) {List<String> re =NewArraylist<string>(); Map<Integer,Integer> map =NewHashmap<integer,integer>(); intSize =s.length (); if(size<=10)returnre; intTMP = 0; for(inti=0;i<10;i++) {tmp= Tmp<<2; TMP= tmp|ToInt (S.charat (i)); } map.put (TMP,1); for(intj=10;j<size;j++) {tmp= ((TMP&0X3FFFF) <<2) |toint (S.charat (j));//first, top 2 position 0 shift left two bit if(Map.containskey (tmp)) {Map.put (Tmp,map.get (TMP)+1); } Else{map.put (tmp,1); }} Set<Integer> keys =Map.keyset (); for(Integer key:keys) {if(Map.get (Key) >1) Re.add (ToString (key)); } returnre; }}
Repeated DNA sequences