2085. 统计出现过一次的公共字符串(简单)

1,问题描述

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

难度:简单

给你两个字符串数组 words1words2 ,请你返回在两个字符串数组中 都恰好出现一次 的字符串的数目。

示例 1:

1
2
3
4
5
6
7
8
输入:words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
输出:2
解释:
- "leetcode" 在两个数组中都恰好出现一次,计入答案。
- "amazing" 在两个数组中都恰好出现一次,计入答案。
- "is" 在两个数组中都出现过,但在 words1 中出现了 2 次,不计入答案。
- "as" 在 words1 中出现了一次,但是在 words2 中没有出现过,不计入答案。
所以,有 2 个字符串在两个数组中都恰好出现了一次。

示例 2:

1
2
3
输入:words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
输出:0
解释:没有字符串在两个数组中都恰好出现一次。

示例 3:

1
2
3
输入:words1 = ["a","ab"], words2 = ["a","a","a","ab"]
输出:1
解释:唯一在两个数组中都出现一次的字符串是 "ab" 。

提示:

  • 1 <= words1.length, words2.length <= 1000
  • 1 <= words1[i].length, words2[j].length <= 30
  • words1[i]words2[j] 都只包含小写英文字母。

2,初步思考

​ 题目本身没有难度,直接使用散列表进行缓存计数就可以解决
​ 主要是里面有一些比较厉害的解法

3,代码处理

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
import java.util.*;

public class _2085统计出现过一次的公共字符串 {

// hashSet处理
public int countWords(String[] words1, String[] words2) {
Map<String, Integer> map1 = new HashMap<>();
Map<String, Integer> map2 = new HashMap<>();
for (String s : words1) {
map1.put(s, map1.getOrDefault(s, 0) + 1);
}
for (String s : words2) {
map2.put(s, map2.getOrDefault(s, 0) + 1);
}

List<String> temp = new ArrayList<>();
map1.forEach((k, v) -> {
if (v == 1 && map2.getOrDefault(k, 0) == 1) {
temp.add(k);
}
});
String[] res = new String[temp.size()];
for (int i = 0; i < temp.size(); i++) {
res[i] = temp.get(i);
}
return res.length;
}

public int countWords_gov(String[] words1, String[] words2) {
Map<String, Integer> map = new HashMap<>();
int result = 0;
for (String s : words1) {
map.put(s, map.getOrDefault(s, 0) + 1000);
}
for (String s : words2) {
map.put(s, map.getOrDefault(s, 0) + 1);
}
for (Integer value : map.values()) {
if (value == 1001) {
result++;
}
}
return result;
}

public int countWords_option(String[] words1, String[] words2) {
Map<String, Integer> cntMap = new HashMap<>();
for (String word : words1) {
if (cntMap.containsKey(word)) {
cntMap.put(word, 2);
} else {
cntMap.put(word, 1);
}
}
int answer = 0;
for (String word : words2) {
int cnt = cntMap.getOrDefault(word, 0);
if ((cnt & 1) == 0) {
continue;
}
if (cnt == 1) {
answer++;
cntMap.put(word, 3);
} else if (cnt == 3) {
answer--;
cntMap.put(word, 4);
}
}
return answer;
}

}