-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0187-repeated-dna-sequences.cpp
More file actions
78 lines (69 loc) · 1.35 KB
/
0187-repeated-dna-sequences.cpp
File metadata and controls
78 lines (69 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "unordered_set"
#include "vector"
#include "string"
using namespace std;
class Solution {
public:
int mask = (1 << 20) - 1;
int charToInt(char ch) {
switch (ch) {
case 'A':
return 0;
case 'C':
return 1;
case 'G':
return 2;
case 'T':
return 3;
}
return 0;
}
string hashToStr(int hash) {
int initial = 3 << 18;
int shift = 18;
string s = "";
for (int i = 0; i < 10; i++) {
switch ((hash & initial) >> shift) {
case 0:
s += 'A';
break;
case 1:
s += 'C';
break;
case 2:
s += 'G';
break;
default:
s += 'T';
break;
}
initial = initial >> 2;
shift -= 2;
}
return s;
}
vector<string> findRepeatedDnaSequences(string s) {
int hash = 0;
unordered_set<int> st;
unordered_set<int> ans;
vector<string> arr;
int j = 0, n = s.size();
while (j < 10 && j < n) {
hash = (hash << 2) | charToInt(s[j]);
j++;
}
st.insert(hash);
while (j < n) {
hash = (hash << 2) | charToInt(s[j]);
hash = hash & mask;
if (st.count(hash)) {
ans.insert(hash);
}
st.insert(hash);
j++;
}
for (auto it : ans)
arr.push_back(hashToStr(it));
return arr;
}
};