Skip to content

[884] Uncommon Words from Two Sentences

https://leetcode.com/problems/uncommon-words-from-two-sentences/description/

  • algorithms
  • Easy (59.79%)
  • Source Code: 884.uncommon-words-from-two-sentences.py
  • Total Accepted: 27.3K
  • Total Submissions: 45K
  • Testcase Example: '"this apple is sweet"\n"this apple is sour"'

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.
python
class Solution(object):
    def uncommonFromSentences(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: List[str]
        """
        A = A.split()
        B = B.split()
        ret = []
        tableA, tableB = {}, {}
        for k in A:
            if k not in tableA:
                tableA[k] = 1
            else:
                tableA[k] += 1

        for k in B:
            if k not in tableB:
                tableB[k] = 1
            else:
                tableB[k] += 1

        # print(tableA, tableB, ret)
        for k in tableA:
            if k not in tableB and tableA[k] == 1:
                ret.append(k)

        for k in tableB:
            if k not in tableA and tableB[k] == 1:
                ret.append(k)

        return ret
#
#
# a, b = "apple apple", "banana"
# a, b = "s z z z s", "s z ejt"
#
# s = Solution()
# print s.uncommonFromSentences(a,b)

Last updated: