
链接:
题解:














- class Solution {
- using ll = unsigned long long;
- ll P = 13331; // 取131会有哈稀冲突
- public:
- vector
findRepeatedDnaSequences(string s) { - int n = s.size();
- vector
f(n+1, 0), p(n+1, 0) ; p[0] = 1; - for(int i=0; i
- f[i+1] = f[i] * P + s[i];
- p[i+1] = p[i] * P;
- }
-
- unordered_map
int> d; - vector
ret; - for(int i=9; i
// 枚举右端点 - int h = f[i+1] - f[i-9] * p[10];
- if(++d[h] == 2) // 第二次出现
- ret.push_back(s.substr(i-9, 10));
- }
- return ret;
- }
- };
-
- class Solution {
- const int L = 10;
- public:
- vector
findRepeatedDnaSequences(string s) { - vector
ans; - unordered_map
int> cnt; - int n = s.length();
- for (int i = 0; i <= n - L; ++i) {
- string sub = s.substr(i, L);
- if (++cnt[sub] == 2) {
- ans.push_back(sub);
- }
- }
- return ans;
- }
- };
下面这两种通过不了:
- class Solution {
- public:
- vector
findRepeatedDnaSequences(string s) { - if (s.size() < 10) {
- return {};
- }
- long ten9 = 1e9 + 7;
- long hhash = 1;
- long B = 256;
- //std::unordered_map
table{{'A', 0}, {'C', 1}, {'G', 2}, {'T', 3}}; - for (int i = 0; i < 9; ++i) {
- hhash = (hhash * B + s[i]) % ten9;
- //hhash = (hhash * B + table[s[i]]) % ten9;
- }
- long P = 1;
- for (int i = 0; i < 9; ++i) {
- P = P * B % ten9;
- }
- std::unordered_map<long, int> hash2index; // hash值对应的最开始字符
- //cout << hhash << endl;
- //hash2index[hhash] = 0;
- std::vector
result; - for (int i = 9; i < s.size(); ++i) {
- hhash = (hhash * B + s[i]) % ten9;
- //long prev = (hhash - table[s[i-10]] * P) % ten9 * B;
- //hhash = (prev + table[s[i]] * B % ten9) % ten9;
- //cout << "i = " << i << " prev = " << prev << " new = " << hhash << endl;
- cout << "i = " << i << " hhash = " << hhash << endl;
- if (hash2index.find(hhash) != hash2index.end()) {
- result.push_back(s.substr(i-9, 10));
- } else {
- hash2index[hhash] = i - 9;
- }
- hhash = (hhash - s[i-9] * P % ten9 + ten9) % ten9;
- }
- return result;
- }
- };
- class Solution {
- public:
- vector
findRepeatedDnaSequences(string s) { - if (s.size() < 10) {
- return {};
- }
- long ten9 = 1e9 + 7;
- long hhash = 1;
- long B = 4;
- std::unordered_map<char, long> table{{'A', 0}, {'C', 1}, {'G', 2}, {'T', 3}};
- for (int i = 0; i < 10; ++i) {
- //hhash = (hhash * B + s[i]) % ten9;
- hhash = (hhash * B + table[s[i]]) % ten9;
- }
- int P = 1;
- for (int i = 0; i < 9; ++i) {
- P = P * B % ten9;
- }
- std::unordered_map<long, int> hash2index; // hash值对应的最开始字符
- cout << hhash << endl;
- hash2index[hhash] = 0;
- std::vector
result; - for (int i = 10; i < s.size(); ++i) {
- long prev = (hhash - table[s[i-10]] * P) % ten9 * B;
- hhash = (prev + table[s[i]] * B % ten9) % ten9;
- cout << "i = " << i << " prev = " << prev << " new = " << hhash << endl;
- if (hash2index.find(hhash) != hash2index.end()) {
- result.push_back(s.substr(i-9, 10));
- } else {
- hash2index[hhash] = i - 9;
- }
- }
- return result;
- }
- };