LeetCode:884. Uncommon Words from Two Sentences - Python

问题描述:

884. 两句话中的不常见单词

给定两个句子 AB 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)

如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。
返回所有不常用单词的列表。
您可以按任何顺序返回列表。

示例 1:

输入:A = “this apple is sweet”, B = “this apple is sour”
输出:[“sweet”,”sour”]

提示:

  • 0 <= A.length <= 200
  • 0 <= B.length <= 200
  • AB 都只包含空格和小写字母。

问题分析:

题目不分大小,总结就好哈。一开始还以为是求并集然后减去交集那,仔细看了,不是。就是求出现次数为1的单词,那就计数呗。(这类题目可以很好的练习一下Python基础知识哈)

Python3实现:

class Solution:
    def uncommonFromSentences(self, A, B):
        count = {}
        for word in A.split():
            count[word] = count.get(word, 0) + 1
        for word in B.split():
            count[word] = count.get(word, 0) + 1
        return [word for word in count if count[word] == 1]

    def uncommonFromSentences1(self, A, B):
        import collections
        count = collections.Counter(A.split())
        count += collections.Counter(B.split())
        return [word for word in count if count[word] == 1]


if __name__ == '__main__':
    A, B = "this apple is sweet", "this apple is sour"
    solu = Solution()
    print(solu.uncommonFromSentences1(A, B))

参考链接:leetcode.com/problems/uncommon-words-from-two-sentences/solution/

声明: 总结学习,大神可以略过哦,有问题可以批评指正哦。

猜你喜欢

转载自blog.csdn.net/XX_123_1_RJ/article/details/81836207