天天看點

LeetCode 884. 兩句話中的不常見單詞

題目

給定兩個句子 A 和 B 。 (句子是一串由空格分隔的單詞。每個單詞僅由小寫字母組成。)

如果一個單詞在其中一個句子中隻出現一次,在另一個句子中卻沒有出現,那麼這個單詞就是不常見的。

傳回所有不常用單詞的清單。

您可以按任何順序傳回清單。

示例 1:

輸入:A = "this apple is sweet", B = "this apple is sour"
輸出:["sweet","sour"]
示例 2:

輸入:A = "apple apple", B = "banana"
輸出:["banana"]           

提示:

0 <= A.length <= 200

0 <= B.length <= 200

A 和 B 都隻包含空格和小寫字母。

解題思路

class Solution:
    def uncommonFromSentences(self, A: str, B: str) -> [str]:
        strList = (A+" "+B).split( )
        print(strList)
        import collections
        retDic = collections.Counter(strList)#合并字典,其中數量為1的就是唯一的
        ret = []
        for key in retDic:
           if retDic[key] == 1:
               ret.append(key)
        return ret