187. 重复的DNA序列

187. 重复的DNA序列

解法一: 哈希

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func findRepeatedDnaSequences(s string) []string {
length := len(s)
if length < 10 {
return []string{}
}
hash := map[string]int{}
str := "0"
ans := []string{}
for i := 0; i < length; i++ {
for len(str) < 10 {
str += string(s[i])
i++
}
str += string(s[i])
str = str[1:]
if hash[str] == 1 {
ans = append(ans, str)
}
hash[str]++
}
return ans
}

解法二: 位运算

go
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
func findRepeatedDnaSequences(s string) []string {
length := len(s)
if length < 10 {
return []string{}
}
num := 0
dict := map[byte]int{
'A': 0,
'C': 1,
'G': 2,
'T': 3,
}
for i := 0; i < 10; i++ {
num = (num << 2) | dict[s[i]]
}
hash := map[int]int{
num: 1,
}
ans := []string{}
for i := 10; i < length; i++ {
num = ((num << 2) | dict[s[i]]) & ((1 << 20) - 1)
if hash[num] == 1 {
sb := strings.Builder{}
for j := i - 9; j <= i; j++ {
sb.WriteString(string(s[j]))
}
ans = append(ans, sb.String())
}
hash[num]++
}
return ans
}
作者

wuhunyu

发布于

2023-11-05

更新于

2023-11-05

许可协议