2085. 统计出现过一次的公共字符串

2085. 统计出现过一次的公共字符串

解法一: 双哈希

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func countWords(words1 []string, words2 []string) int {
hash1 := make(map[string]int, len(words1))
hash2 := make(map[string]int, len(words2))
for _, word := range words1 {
hash1[word]++
}
for _, word := range words2 {
hash2[word]++
}
ans := 0
for word, count := range hash1 {
if count == 1 && hash2[word] == 1 {
ans++
}
}
return ans
}

解法二: 单哈希

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func countWords(words1 []string, words2 []string) int {
hash := make(map[string]int, len(words1))
for _, word := range words1 {
hash[word]++
}
ans := 0
for _, word := range words2 {
if count, exists := hash[word]; exists {
if count == 1 {
ans++
hash[word] = -1
} else if count == -1 {
ans--
delete(hash, word)
}
}
}
return ans
}
作者

wuhunyu

发布于

2024-01-12

更新于

2024-01-12

许可协议