884. Uncommon Words from Two Sentences (easy) 

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\"]
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 

收藏 打印