「每日LeetCode」2022年6月24日

本文最后更新于:2023年3月19日 晚上

389.找不同

389.找不同

Category Difficulty Likes Dislikes
algorithms Easy (68.27%) 328 -

Tags
Companies
给定两个字符串 s 和 t ,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。

示例 1:
输入:s = “abcd”, t = “abcde” 输出:“e” 解释:‘e’ 是那个被添加的字母。
示例 2:
输入:s = “”, t = “y” 输出:“y”

提示:

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s 和 t 只包含小写字母

Discussion | Solution

思路

按题意模拟即可,使用 map 记录

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
* @lc app=leetcode.cn id=389 lang=javascript
*
* [389] 找不同
*/

// @lc code=start
/**
* @param {string} s
* @param {string} t
* @return {character}
*/
var findTheDifference = function (s, t) {
const map = {};

for (const char of s) {
if (map[char]) map[char]++;
else map[char] = 1;
}

for (const char of t) {
if (map[char] > 0) {
map[char]--;
} else {
return char;
}
if (map[char] === 0) {
delete map[char];
}
}
};
// @lc code=end