1. 程式人生 > >Leetcode 884. 兩句話中的不常見單詞

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

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

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

返回所有不常用單詞的列表。

您可以按任何順序返回列表。

 

示例 1:

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

示例 2:

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

 

提示:

  1. 0 <= A.length <= 200
  2. 0 <= B.length <= 200
  3. A 和 B 都只包含空格和小寫字母。

 

統計兩個字元中,只出現一次的單詞,即可。涉及到字串分割,使用Python的split函式比較方便,最後是個map統計單詞出現的個數

class Solution:
    def uncommonFromSentences(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: List[str]
        """
        A=A.split()
        B=B.split()
        dictA = {}
        res=[]
        for key in A:
            dictA[key] = dictA.get(key, 0) + 1
        
        for key in B:
            dictA[key] = dictA.get(key, 0) + 1
        
        for key in dictA:
            if dictA[key]==1:
                res.append(key)
        
        return res