# 找不同(389)
# 题目
给定两个字符串 s
和 t
,它们只包含小写字母。
字符串 t
由字符串 s
随机重排,然后在随机位置添加一个字母。
请找出在 t
中被添加的字母。
# 示例
输入:s = "abcd"
, t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。
输入:s = ""
, t = "y"
输出:"y"
输入:s = "a"
, t = "aa"
输出:"a"
输入:s = "ae"
, t = "aea"
输出:"a"
# 提示
- 0 <= s.length <= 1000
- t.length == s.length + 1
- s 和 t 只包含小写字母
# 算法
# 数组
使用数组保存每个字母出现的次数,用t
中字母出现的次数减去s
中字母出现的次数就可以得到多于字母的下标,继而求出多于字母
export const findTheDifference = (s, t) => {
const arr = new Array(26).fill(0);
Array.prototype.forEach.call(t, (n) => arr[n.charCodeAt() - 97]++);
Array.prototype.forEach.call(s, (n) => arr[n.charCodeAt() - 97]--);
return String.fromCharCode(arr.indexOf(1) + 97);
};
1
2
3
4
5
6
2
3
4
5
6
# 求和
将两个字符串的每个字母的ASCII码分别加起来,他们的差值就是多于字母的ASCII码
export const findTheDifference = (s, t) => {
return String.fromCharCode(
Array.prototype.reduce.call(t, (acc, cur) => (acc += cur.charCodeAt()), 0) -
Array.prototype.reduce.call(s, (acc, cur) => (acc += cur.charCodeAt()), 0)
);
};
1
2
3
4
5
6
2
3
4
5
6
# 位运算
在两个字符串中重复出现的数出现次数是偶数,使用交换律
和结合律
可以异或运算他们的ASCII码为0
,只出现一次的字母的ASCII码就是异或运算最后的结果
export const findTheDifference = (s, t) => {
let ret = 0;
Array.prototype.forEach.call(s, (n) => (ret ^= n.charCodeAt()));
Array.prototype.forEach.call(t, (n) => (ret ^= n.charCodeAt()));
return String.fromCharCode(ret);
};
1
2
3
4
5
6
2
3
4
5
6