「每日LeetCode」2022年6月12日

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

  1. 查找和替换模式

890. 查找和替换模式

你有一个单词列表 words 和一个模式 pattern,你想知道 words 中的哪些单词与模式匹配。
如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。
(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)
返回 words 中与给定模式匹配的单词列表。
你可以按任何顺序返回答案。

示例:
输入:words = [“abc”,”deq”,”mee”,”aqq”,”dkd”,”ccc”], pattern = “abb” 输出:[“mee”,”aqq”] **解释: **”mee” 与模式匹配,因为存在排列 {a -> m, b -> e, …}。 “ccc” 与模式不匹配,因为 {a -> c, b -> c, …} 不是排列。 因为 a 和 b 映射到同一个字母。

提示:

  • 1 <= words.length <= 50
  • 1 <= pattern.length = words[i].length <= 20

思路

按题意模拟即可,从 a 开始转换字符串

解答

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
33
34
35
36
/**
* @param {string[]} words
* @param {string} pattern
* @return {string[]}
*/
var findAndReplacePattern = function (words, pattern) {
const res = [];

const patternmap = new Map([[pattern[0], "a"]]);
let patternStr = "";

for (const char of pattern) {
if (!patternmap.has(char)) {
cur = String.fromCharCode(cur.charCodeAt() + 1);
} else cur = patternmap.get(char);
patternmap.set(char, cur);
patternStr += cur;
}

for (const word of words) {
const map = new Map([[word[0], "a"]]);
let cur = "a",
str = "";
for (const char of word) {
if (!map.has(char)) {
cur = String.fromCharCode(cur.charCodeAt() + 1);
} else cur = map.get(char);
map.set(char, cur);
str += cur;
}
if (str === patternStr) {
res.push(word);
}
}
return res;
};