389.找不同

给定两个字符串 s 和 t,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例 1:

1
2
3
输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。

示例  2:

1
2
输入:s = "", t = "y"
输出:"y"

示例 3:

1
2
输入:s = "a", t = "aa"
输出:"a"

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {string} s
* @param {string} t
* @return {character}
*/
var findTheDifference = function (s, t) {
let arr = new Array(26).fill(0);

for (let i = 0; i < s.length; i++) {
arr[s.codePointAt(i) - "a".charCodeAt()]++;
}
for (let i = 0; i < t.length; i++) {
let key = t.codePointAt(i) - "a".charCodeAt();
arr[key]--;
if (arr[key] < 0) {
return String.fromCharCode(key + "a".charCodeAt());
}
}
return "";
};

代码实现 2:

1
2
3
4
5
6
7
8
9
10
var findTheDifference = function (s, t) {
let sum = 0;
for (let i = 0; i < t.length; i++) {
sum += t.codePointAt(i);
}
for (let i = 0; i < s.length; i++) {
sum -= s.codePointAt(i);
}
return String.fromCharCode(sum);
};