LC.P187[重复的DNA序列]

方法一:滑动窗口+哈希表

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public List<String> findRepeatedDnaSequences(String s) {
List<String> ans = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i + 10 <= s.length(); ++i) {
String cur = s.substring(i, i + 10);
if (map.merge(cur, 1, Integer::sum) == 2) ans.add(cur);
}
return ans;
}
}
  • 时间复杂度:每次检查以s[i]为结尾的子串,需要构造出新的长度为$10$的字符串。令$C = 10$,复杂度为$O(n \times C)$
  • 空间复杂度:$O(n)$

方法二:滑动窗口+哈希表+位运算

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
class Solution {
static int length = 10;
Map<Character, Integer> map = new HashMap<>() {{
put('A', 0);
put('C', 1);
put('G', 2);
put('T', 3);
}};

public List<String> findRepeatedDnaSequences(String s) {
List<String> ans = new ArrayList<>();
int n = s.length();
if (n <= length) return ans;
int x = 0;
for (int i = 0; i < length - 1; ++i) {
x = (x << 2) | map.get(s.charAt(i));
}
Map<Integer, Integer> cnt = new HashMap<>();
for (int i = 0; i + length <= n; ++i) {
x = ((x << 2) | map.get(s.charAt(i + length - 1))) & ((1 << (length * 2)) - 1);
cnt.put(x, cnt.getOrDefault(x, 0) + 1);
if (cnt.get(x) == 2) {
ans.add(s.substring(i, i + length));
}
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$