日野弥生:勉強しよう
LeetCode 389 - 找不同
发表于2025年05月13日
用python自带的Counter可以简单实现。
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
sCounter = Counter(s)
for i in t:
if i not in sCounter:
return i
else:
if sCounter[i] == 0:
return i
else:
sCounter[i] -= 1
return ""
求和法
由于题目提到s和t只包含小写字母,所以可以把ASCII码求出来求差。
def findTheDifference(s: str, t: str) -> str:
# map(ord , t)是对列表t求出所有的ascii码数;然后用sum求和,和的差再用chr()反求字母即可
return chr(sum(map(ord, t)) - sum(map(ord, s)))
位运算
随机新增的字母,它在两个字符串组合成的总字符串中,一定只出现过奇数次。利用异或运算的性质可以求取。
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
ret = 0
for ch in s:
ret ^= ord(ch)
for ch in t:
ret ^= ord(ch)
return chr(ret)