「每日LeetCode」2021年5月9日

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

Lt884. 两句话中的不常见单词

884. 两句话中的不常见单词

给定两个句子 AB 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)
如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的
返回所有不常用单词的列表。
您可以按任何顺序返回列表。
示例 1:

1
2
输入:A = "this apple is sweet", B = "this apple is sour"
输出:["sweet","sour"]

示例  2:

1
2
输入:A = "apple apple", B = "banana"
输出:["banana"]

提示:

  1. 0 <= A.length <= 200
  2. 0 <= B.length <= 200
  3. AB 都只包含空格和小写字母。

思路

转为数组后,拼接起来后,用哈希表统计次数,之后遍历哈希表,频次为 1 加入结果数组

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @param {string} A
* @param {string} B
* @return {string[]}
*/
var uncommonFromSentences = function (A, B) {
const res = [];
const map = new Map();
for (const word of A.split(" ").concat(B.split(" ")))
map.set(word, map.has(word) ? map.get(word) + 1 : 1);
for (const [word, times] of map) {
if (times === 1) res.push(word);
}
return res;
};