Leetcode 389.找不同
1 题目描述(Leetcode题目链接)
给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
输入:
s = "abcd"
t = "abcde"
输出:
e
解释:
'e' 是那个被添加的字母。
2 题解
添加了一个字符,意味着两个字符串所有的字符只有一个字符的数量是奇数个,因此可以用哈希表来记录每种字符的数量,找出奇数个的那个字符就是新添加的字符。
还可以思考使用异或来做,所有字符转为整数值后再异或起来剩下的就是新添加字符的整数值,返回这个整数值对应的字符就好了。
做法多种多样,这样的小题可以锻炼锻炼思考问题的角度。
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
retv = ord(t[-1])
for i in range(len(s)):
retv ^= ord(s[i])
retv ^= ord(t[i])
return chr(retv)
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
for i in range(len(t)):
if t.count(t[i]) != s.count(t[i]):
return t[i]
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
return chr(sum(map(ord, t)) - sum(map(ord, s)))