给定两个字符串 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
"""
ch = 0
for c in s+t:
ch ^= ord(c)
return chr(ch)
还是用到上一题的解法,0 与任何数异或都为任何数本身,相同的两个数异或为 0 。
ord 函数把字符串转化成十进制的数字,chr 函数把十进制的数字转化成字符串。
第二种方式
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
sum1 = 0
sum2 = 0
for i in t:
sum1 += ord(i)
for i in s:
sum2 += ord(i)
return chr(sum1 - sum2)
解题思路一样。