LeetCode(easy)-884. Uncommon Words from Two Sentences

884. Uncommon Words from Two Sentences
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”]
題目:
我們給出了兩個句子A和B.(一個句子是一串空格分隔的單詞。每個單詞只包含小寫字母。)如果一個單詞在其中一個句子中只顯示一次,並且不出現在另一個句子中,則該單詞不常見。返回所有不常見單詞的列表。可以按任何順序返回列表。
解法一:

class Solution(object):
    def uncommonFromSentences(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: List[str]
        """
        dictionary = {}
        res = []
        for word in A.split(" "):
            if word in dictionary:
                dictionary[word] +=1
            else:
                dictionary[word] =1
        for word in B.split(" "):
            if word in dictionary:
                dictionary[word] +=1
            else:
                dictionary[word] =1
        for word in dictionary:
            if dictionary[word] ==1:
                res.append(word)
        return res

Runtime: 24 ms

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章