Skip to content

389 find the difference

389. Find the Difference

题目: https://leetcode.com/problems/find-the-difference/

难度:

Easy

用个字典来记录,把s加进去,把t减掉,最后剩下那个要么个数为1,要么个数为-1

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        res = {}
        for i in s:
            res[i] = res.get(i, 0) + 1
        for j in t:
            res[j] = res.get(j, 0) - 1
        for key in res:
            if abs(res[key]) == 1:  # 这里用 abs 是因为新增加的那个字母在 s 中可能未出现过
                return key

还有一个简单的方法

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        from collections import Counter
        return list((Counter(t) - Counter(s)).keys()).pop()


回到顶部