题目来源:https://leetcode-cn.com/problems/find-the-difference/submissions/
给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入:
s = "abcd"
t = "abcde"
输出:
e
思路:
一个直接的想法就是用counter做字符计数,t中某个字符不存在与s或者某个字符出现的次数与s中该字符出现的次数不一致,则返回该字符。时间复杂度是O(n).
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
from collections import Counter
if len(s) == 0:
return t
s_counter = Counter(s)
t_counter = Counter(t)
for key in t_counter:
if key not in s_counter:
return key
elif t_counter[key] != s_counter[key]:
return key
看题解发现还有一个比较tricky的解法,利用异或运算的性质,一个值连续对另一个值做两次异或,会返回它本身,异或运算是可交换的。其实很好理解两个相同的数做异或运算结果为0,而一个数与0做异或结果就是它本身。可以利用这个性质去消除字符串中的“对子“。
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
new_s = s + t
res = 0
for i in new_s:
res ^= ord(i)
return chr(res)