LeetCode 884. 兩句話中的不常見單詞(python)
阿新 • • 發佈:2018-12-19
給定兩個句子 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
都只包含空格和小寫字母。
python
class Solution: def uncommonFromSentences(self, A, B): """ :type A: str :type B: str :rtype: List[str] """ res=[] a=A.split(' ') b=B.split(' ') dic1={} dic2={} for i in range(len(a)): if a[i] not in dic1: dic1[a[i]]=1 else: dic1[a[i]]+=1 for i in range(len(b)): if b[i] not in dic2: dic2[b[i]]=1 else: dic2[b[i]]+=1 for key in dic1: if dic1[key]==1 and key not in dic2: res.append(key) for key in dic2: if dic2[key]==1 and key not in dic1: res.append(key) return res