LeetCode #389. Find the Difference

题目

389. Find the Difference


解题方法

先统计两个字符串中每个字母的出现次数,记为dic_s和dic_t,先遍历dic_s,找一个在dic_t中没出现的字母,或者在dic_t中出现了但是频数和dic_s中不一样的字母,找到了就break不做了,要是没找到就再去dic_t中找和dic_s中不一样的字母,最后返回。
时间复杂度:O(n)
空间复杂度:O(n)


代码

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        dic_s = collections.Counter(s)
        dic_t = collections.Counter(t)
        
        rat = None
        for key in dic_s.keys():
            if key not in dic_t or dic_t[key] != dic_s[key]:
                rat = key
                break
        
        if not rat:
            for key in dic_t.keys():
                if key not in dic_s or dic_s[key] != dic_t[key]:
                    rat = key
                    break
        return rat
posted @ 2020-12-08 09:05  老鼠司令  阅读(56)  评论(0编辑  收藏  举报