【Leetcode_总结】389. 找不同

Q:

给定两个字符串 s 和 t,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例:

输入:
s = "abcd"
t = "abcde"

输出:
e

解释:
'e' 是那个被添加的字母。

思路:用一个list统计字符个数,在字符串s中的加1,在字符串t中的减1,最后寻找序号为-1的位置对应的字符

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        if s == "":
            return t
        temp = [0 for _ in range(26)]
        for i in range(len(s)):
            temp[ord(s[i])-ord('a')] +=1
        for tt in t:
            temp[ord(tt) - ord('a')] -=1
        # print(temp)
        return chr(temp.index(-1)+ord('a'))

一些更加高效的代码:

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        s1=list(set(s))
        t1=list(set(t))

        d={}
        for i in range(len(s1)):
            d[s1[i]]=s.count(s1[i])
        for j in range(len(t1)):
            if t1[j] not in d:
                return t1[j]
            else:
                if d[t1[j]] != t.count(t1[j]):
                    return t1[j]
class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        sums = 0
        sumt = 0
        for item in s:
            sums += ord(item)
        for item in t:
            sumt += ord(item)
        return chr(sumt-sums)

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/83189048
今日推荐