Description
We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You may return the list in any order.
Example 1:
Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]
Example 2:
Input: A = "apple apple", B = "banana"
Output: ["banana"]
Note:
- 0 <= A.length <= 200
- 0 <= B.length <= 200
- A and B both contain only spaces and lowercase letters.
分析
题目的意思是:给定两个句子,找出其中的uncommon的句子。这道题换句话说找出词频为1的单词,如果想到这个就很好了,我看标准解答直接用一个字典统计词频然后把词频为1的找出来就行了。
- 我的解法有点中规中矩,用了两个字典,分别统计词频,然后取出词频为1的单词,相比于标准答案稍稍复杂了一点,哈哈哈。
代码
class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
dA=defaultdict(int)
dB=defaultdict(int)
arrA=A.split()
arrB=B.split()
for item in arrA:
dA[item]+=1
for item in arrB:
dB[item]+=1
res=[]
for k,v in dA.items():
if(v==1 and k not in dB):
res.append(k)
for k,v in dB.items():
if(v==1 and k not in dA):
res.append(k)
return res