给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入:
s = "abcd"
t = "abcde"
输出:
e
解释:
'e' 是那个被添加的字母。
第一种思路:
转成list之后求和,s和t的和之差就是相差的那个字母。
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
return chr(sum(ord(i) for i in list(t)) - sum(ord(j) for j in list(s)))
第二种思路:
利用异或XOR来进行位运算。
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
res = 0
for i in s:
res ^= ord(i) - 97
for i in t:
res ^= ord(i) - 97
return chr(res + 97)
第三种思路:
已知插入的一定是字母,所以可以遍历整个字母表+count函数来确定是哪一个字母。
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if s.count(char) != t.count(char):
return char