leetcode_389 找不同

95 阅读1分钟

要求

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

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

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

示例 1:

输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。

示例 2:

输入:s = "", t = "y"
输出:"y"

示例 3:

输入:s = "a", t = "aa"
输出:"a"

示例 4:

输入:s = "ae", t = "aea"
输出:"a"

详解代码

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        return chr(sum(ord(i) for i in list(t)) - sum(ord(j) for j in list(s)))

另一解法

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        res = 0
        for i in s:
            res ^= ord(i) - 97
        for i in t:
            res ^= ord(i) - 97
        return chr(res + 97)

第三种解法

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        alphabet = "abcdefghijklmnopqrstuvwxyz"
        for i in t:
            if s.count(i) != t.count(i):
                return i

image.png

解题思路:第一种解法:我们使用字母的ascii码加法求出来差值在将差值还原回字符即可;第二种解法:使用异或的方式,我们知道相同的值进行异或得到0,即可消掉数据,最后剩下的就是不同的字母;第三种解法:我们对数据进行遍历,找到不同的,输出即可。