187.
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在地图绕过内存限制。 只有四个可能的字符a、c、g和t,但我希望每字母使用3位,而不是2位。 为什么?代码更容易编写。 一个是0x41,C是0x43,G 0x47,T是0x54。还是没看到吗?让我用八进制写。 a是0101,c是0103,g是0107,t是0124。八进制的最后一个数字对所有四个字母都是不同的。这就是我们所需要的! 我们可以简单地使用s i i和7获得最后一位数,这是最后的3位,它比查找表或开关或一组IF和其他的要容易得多,对吗? 我们真的不需要从内部产生的子串出现的次数,计算,我们可以把串成的结果当计数变为2,所以不会有任何重复的结果。
vector<string> findRepeatedDnaSequences(string s) { unordered_map<int, int> m; vector<string> r; int t = 0, i = 0, ss = s.size(); while (i < 9) t = t << 3 | s[i++] & 7; while (i < ss) if (m[t = t << 3 & 0x3FFFFFFF | s[i++] & 7]++ == 1) r.push_back(s.substr(i - 10, 10)); return r; }