LeetCode--Python解析【Find the Difference】(389)

本文介绍了通过两种不同的方法来找出两个字符串中唯一不同的字符。方法一采用列表操作实现,而方法二则利用哈希表优化查找过程,提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:


方法1:

这道题的的解法类似于LeetCode--Python解析【Intersection of Two Arrays II】(350),第一种方法也用list的方法来解

将s转为list,然后遍历t中的字符,若存在于s中,则删除s中的该字符

若s中无该字符,则证明该字符是被添加的字符,返回该字符

class Solution:
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        x = list(s)
        for i in range(len(t)):
            if t[i] in x:   
                x.remove(t[i])  
            else: 
                return t[i]
        
方法2:
还是使用hash table来做

遍历s中的字符,设置一个dict

将键值设置为字符,value为出现次数

接下来遍历t中的字符,若该字符存在于dict中

则dict中该元素对应的value-1

若不存在与dict中,则该字符便是被添加的字符

将该字符返回

class Solution:
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        dict1 = {}
        for i in range(len(s)):
            if s[i] not in dict1:
                dict1[s[i]] = 1
            else:
                dict1[s[i]] += 1 
        for i in range(len(t)):
            if t[i] in dict1 and dict1[t[i]] > 0:
                dict1[t[i]] -= 1
            else:return t[i]

此方法由于使用了Hash Table来储存,所以时间复杂度上优于第一种方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值