https://leetcode-cn.com/problems/find-the-difference/
描述
给定两个字符串 s和t,它们只包含小写字母。
字符串 t和 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入:
s = "abcd"
t = "abcde"
输出:
e
解释:
'e' 是那个被添加的字母。
分析
传统思路就是遍历字符串,再依次判断移除。
var findTheDifference = function(s, t) {
let len = t.length
for(let i = 0;i < len;i++) {
let index = s.indexOf(t[i])
if (index >= 0) {
s = s.replace(t[i], '')
} else {
return t[i]
}
}
};
看了评论,可以使用异或。
首先我们知道
1 ^ 1 = 0
0 ^ 0 = 0
0 ^ a = a
a ^ a = 0
由于这两个字符串只有一个字符不相同,所以只需要不断的异或,最后剩下的字符就是添加的了
let findTheDifference = function(s, t) {
let code = 0;
for (let c of s + t) {
code ^= c.charCodeAt(0);
}
return String.fromCharCode(code);
};