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

题目:


方法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来储存,所以时间复杂度上优于第一种方法。

猜你喜欢

转载自blog.csdn.net/zjrn1027/article/details/80158403