LeetCode #389. Find the Difference

Posted 老鼠司令

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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


以上是关于LeetCode #389. Find the Difference的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 389 Find the difference

LeetCode 389. Find the Difference

LeetCode_389. Find the Difference

leetcode No389. Find the Difference

leetcode No389. Find the Difference

LeetCode:Find the Difference_389