1、暴力破解
首先想到的是暴力破解,用两个循环遍历列表,然后将单词出现的情况都记录在一个字典里面。最后遍历字典找到满足条件的值。
class Solution:
def countWords(self, words1: List[str], words2: List[str]) -> int:
map1 = {}
for wd in words1:
if wd in map1:
map1[wd] += 1
else:map1[wd] = 1
map2 = {}
for wd in words2:
if wd in map2:
map2[wd] += 1
else:map2[wd] = 1
# print(map1,map2)
count = 0
for key, value in map1.items():
if key in map2 and map1[key] == 1 and map2[key] == 1:
count += 1
return count
2、哈希
from collections import Counter
list1 = ["a", "a", "a", "b", "c", "c", "f", "g", "g", "g", "f"]
dic = Counter(list1)
print(dic)
#结果:次数是从高到低的
#Counter({'a': 3, 'g': 3, 'c': 2, 'f': 2, 'b': 1})
print(dict(dic))
#结果:按字母顺序排序的
#{'a': 3, 'b': 1, 'c': 2, 'f': 2, 'g': 3}
print(dic.items()) #dic.items()获取字典的key和value
#结果:按字母顺序排序的
#dict_items([('a', 3), ('b', 1), ('c', 2), ('f', 2), ('g', 3)])
print(dic.keys())
#结果:
#dict_keys(['a', 'b', 'c', 'f', 'g'])
print(dic.values())
#结果:
#dict_values([3, 1, 2, 2, 3])
print(sorted(dic.items(), key=lambda s: (-s[1])))
#结果:按统计次数降序排序
#[('a', 3), ('g', 3), ('c', 2), ('f', 2), ('b', 1)]
for i, v in dic.items():
if v == 1:
print(i)
#结果:
#b
解题代码
class Solution:
def countWords(self, words1: List[str], words2: List[str]) -> int:
cnt1 = Counter(words1)
cnt2 = Counter(words2)
return sum(v == 1 and cnt2[w] == 1 for w,v in cnt1.items())