Use 2 Set to store the substrings. If there’s a duplicate, then add to the second set. After the loop, addAll(set2) to list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
publicclassSolution{
public List<String> findRepeatedDnaSequences(String s){
Set<String> set = new HashSet<>();
Set<String> set2 = new HashSet<>();
List<String> lst = new ArrayList<>();
for (int i = 0; i + 10 <= s.length(); i++) {
String sub = s.substring(i, i + 10);
if (!set.add(sub)) {
set2.add(sub);
}
}
lst.addAll(set2);
return lst;
}
}
bit manipulation
There are only 4 kinds of character in the String: A, C, G and T. Ideally, we only need 2 bits to encode these four characters:
1
2
3
4
A: 00
C: 01
G: 10
T: 11
So for entire 10-letter-substring, we only need a total of 2 * 10 = 20 bits (4 bytes) to store the substring. Compared to the naive way, 20 bytes are used.
Then, combined with bit shifting, we could use our own encoding system.
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
publicclassSolution{
public List<String> findRepeatedDnaSequences(String s){