Topic
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"].
Resolution
Test instructions: Find all substrings with a length of 10 that are more than 1 in the DNA sequence.
I think the problem given by the example, in addition to the given two substrings, there are "acccccaaaa", "aacccccaaa", "AAACCCCCAA", "Aaaaccccca" also meet the conditions.
Reference https://oj.leetcode.com/discuss/24478/i-did-it-in-10-lines-of-c Let me explain the idea:
First look at this problem of tags is hash table and bit manipulation, then how to convert the string into a bit operation? We first look at the ASCII code for the letter "A" "C" "G" "T", respectively, 65, 67, 71, 84, binary represented as 1000001, 1000011, 1000111, 1010100. You can see that the latter four bits are different, so use the latter four bits to differentiate between the four letters. A letter with 3bit to distinguish, then 10 letters with 30bit is enough. This 0~9 character is represented by the 29th to No. 0 decimal table of int, and then the 30bit is converted to int as the key of the substring and placed in the Hashtable to determine whether the substring has occurred.
"Java Code"
public class Solution {public list<string> findrepeateddnasequences (String s) { list<string> ans = 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) { Ans.add (s.substring (i-9), i + 1 )); Map.put (key, 2); } } return ans; }}
Added
If you do not remember a,c,g,t ASCII code, and do not want to calculate their binary representation, then you can use an alternative method, that is, the a,c,g,t map to 0,1,2,3, so that with two bit can distinguish them 00,01,10,11. There is a substring of length 10, and the four characters can be distinguished by 3bit, add up to a total of 30bit, if the length of the substring longer, or more than the number of characters need more than 3bit to distinguish, a total of bit more than 32, then the use of mapping is a good solution. Refer to Http://bookshadow.com/weblog/2015/02/06/leetcode-repeated-dna-sequences/
"Leetcode" repeated DNA sequences problem solving report