您的当前位置:首页正文

【Leetcode】884. Uncommon Words from Two Sentences

2024-12-02 来源:个人技术集锦

class Solution1(object):
    """
    stupid dictionary method
    """
    def uncommonFromSentences(self, A, B):
        A, B = A.split(), B.split()
        dictA, dictB ={}, {}
        for char in A:
            dictA[char] = dictA.get(char, 0) + 1
        for char in B:
            dictB[char] = dictB.get(char, 0) + 1
        result = []
        for key in dictA:
            if dictA[key] == 1 and key not in dictB:
                result.append(key)
        for key in dictB:
            if dictB[key] == 1 and key not in dictA:
                result.append(key)
        return result


class Solution2(object):
    """
    use set
    """
    def uncommonFromSentences(self, A, B):
        A, B  = A.split(), B.split()
        result  = [ele for ele in (set(A) - set(B)) if A.count(ele) ==1] + [ele for ele in (set(B)- set(A)) if B.count(ele) == 1]
        return result

class Solution3(object):
    def uncommonFromSentences(self, A, B):
        A = A.split() + B.split()
        from collections import  Counter
        return [k for k,v in Counter(A).items() if v ==1]
x =Solution3()
print(x.uncommonFromSentences("s z z z s","s z ejt"))


显示全文