版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/85090218
884. Uncommon Words from Two Sentences (easy)
We are given two sentences
A
andB
. (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"]
首先要满足出现only once
其次是异或,即只在A中出现或只在B中出现
class Solution:
def uncommonFromSentences(self, A, B):
"""
:type A: str
:type B: str
:rtype: List[str]
"""
uncommon = []
AList = A.split()
BList = B.split()
Acount = collections.Counter(AList)
Bcount = collections.Counter(BList)
Aset = {key for key,count in Acount.items() if count == 1}
Bset = {key for key,count in Bcount.items() if count == 1}
ABset = set(AList) & set(BList)
return list({x for x in Aset^Bset if x not in ABset})
Runtime: 36 ms, faster than 98.82% of Python3