1、题目
给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 请找出在 t 中被添加的字母。
示例:
输入:
s = “abcd”
t = “abcde”
输出:
e
解释:
‘e’ 是那个被添加的字母。
2、分析
题目要求找到t中s添加的那个字母,我首先想到将s,t排序然后利用ascall值进行判断,当二者相同时即为正确的结果.
3、代码
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
s = sorted(s)
t = sorted(t)
for i in range(97, 97+26):
if sorted(s + list(chr(i))) == t:
return (chr(i))
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
ret = 0
for c in s + t:
ret ^= ord(c)
return chr(ret)
4、结果
执行用时 :56 ms, 在所有 Python3 提交中击败了17.25% 的用户
内存消耗 :13.2 MB, 在所有 Python3 提交中击败了51.80%的用户
5、优化
在评论区有人在使用异或(^)运算将速度提升到了98%,所以去学习一下使用一些简单的符号运是很有必要的.
望您:
“情深不寿,强极则辱,谦谦君子,温润如玉”。