给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入: s = "abcd" t = "abcde" 输出: e 解释: 'e' 是那个被添加的字母。
第一种方法
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
sumt=0;sums=0
for t1 in t:
sumt+=ord(t1)#字符转换成十进制数
for s1 in s:
sums+=ord(s1)
return chr(sumt-sums)
第二种方法
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
#通过异或操作
ch=0
for c in s+t:
ch^=ord(c)
return chr(ch)
![](https://i-blog.csdnimg.cn/blog_migrate/9bfa46f4b051781d16c93f66d701f82b.png)