文章目录
题目
给定两个字符串 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”
提示:
0 <= s.length <= 1000 t.length == s.length + 1 s 和 t 只包含小写字母
解题思路
内置函数Counter
可以对 s 进行字母计数,遍历 t 的时候,如果计数小于 000,那么表示这个字母在 t 中出现得更能多一些,返回这个字母就行了。
异或或者相减
t 只比 s 多了一个字母,那么s+t之后相当于 只有 1 个字母出现了奇数次,其它字母全部出现了偶数次。然后对s+t异或,那么最后的结果就是多的字母
或者t的ASCII码直接与s的相减,得到的也是多出来的字母的ASCII码,最后转化即可。
代码
# Counter
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
return list(Counter(t) - Counter(s))[0]
# 异或
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
return chr(reduce(xor, map(ord, s + t)))
# 相减
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
return chr(sum(map(ord, t)) - sum(map(ord, s)))