统计出现过一次的公共字符串
难度:
标签:
题目描述
代码结果
运行时间: 16 ms, 内存: 17.0 MB
/*
题目思路:
1. 使用 Java Stream 处理两个字符串数组,分别统计每个字符串的出现次数。
2. 过滤出在两个数组中都恰好出现一次的字符串,并统计数量。
*/
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Solution {
public int countWords(String[] words1, String[] words2) {
// 统计 words1 中每个字符串的出现次数
Map<String, Long> count1 = Arrays.stream(words1)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// 统计 words2 中每个字符串的出现次数
Map<String, Long> count2 = Arrays.stream(words2)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// 过滤并统计在两个数组中都恰好出现一次的字符串数量
return (int) count1.entrySet().stream()
.filter(e -> e.getValue() == 1 && count2.getOrDefault(e.getKey(), 0L) == 1)
.count();
}
}
解释
方法:
本题的解决方案通过使用Python的collections.Counter类来创建两个字典,分别统计words1和words2中每个字符串的出现次数。然后,遍历words1的计数器(cnt1),检查每个字符串在两个数组中是否都恰好出现了一次。如果一个字符串在words1中出现一次,并且在words2中也出现一次,这个字符串就符合条件。最后,对所有符合条件的字符串计数,得到最终结果。
时间复杂度:
O(n + m)
空间复杂度:
O(n + m)
代码细节讲解
🦆
在计算字符串出现次数时,为什么选择使用Python的collections.Counter类而不是手动维护字典或使用其他数据结构?
▷🦆
如果words1或words2其中一个为空数组,这种情况在当前算法中是如何处理的?
▷🦆
在处理大数据集时,如何优化当前算法以降低内存使用或提高执行效率?
▷