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

Note:

  • 0 <= A.length <= 200
  • 0 <= B.length <= 200
  • A and B both contain only spaces and lowercase letters.

Solution in python:

class Solution:
    def uncommonFromSentences(self, A: str, B: str) -> List[str]:
        alist = A.split()
        blist = B.split()
        adic = dict()
        bdic = dict()
        for item in alist:
            if item not in adic.keys():
                adic[item] = 1
            else:
                adic[item] += 1
        for item in blist:
            if item not in bdic.keys():
                bdic[item] = 1
            else:
                bdic[item] += 1

        aset = set(item for item in adic.keys() if adic[item] == 1 and item not in bdic.keys())
        bset = set(item for item in bdic.keys() if bdic[item] == 1 and item not in adic.keys())
        return aset|bset
最后修改日期: 2021年2月22日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。