[LeetCode]#2085. Count Common Words With One Occurrence
2 min readDec 3, 2021
Environment: Python 3.8
Key technique: set, list
Given two string arrays words1
and words2
, return the number of strings that appear exactly once in each of the two arrays.
Example 1:
Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
Output: 2
Explanation:
- "leetcode" appears exactly once in each of the two arrays. We count this string.
- "amazing" appears exactly once in each of the two arrays. We count this string.
- "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.
- "as" appears once in words1, but does not appear in words2. We do not count this string.
Thus, there are 2 strings that appear exactly once in each of the two arrays.
Analysis:
- Get intersection between words1 and words2
- Find is there only one string in words1 and words2 based on step1 result.
- return string number
Solution:
class Solution:
def countWords(self, words1, words2):
same_w=list(set(words1) & set(words2))
ans=0
for i in same_w:
if words1.count(i)==1 and words2.count(i)==1:
ans+=1
return ans
Submissions: