持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第17天,点击查看活动详情
题目
你有一个单词列表 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 <= 501 <= pattern.length = words[i].length <= 20
思考
本题难度中等。
首先是读懂题意。给出一个单词列表 words 和一个模式 pattern,我们需要知道 words 中的哪些单词与模式匹配。匹配的意思是比如字符串'mee'和'abb'是匹配的,而'abc'或'meemee'与'abb'是不匹配的。
我们可以使用哈希表的方法来解决这个问题。对于单词列表 words,我们可以逐个判断 words 中的每个单词 word 是否与 pattern 匹配。如果 match(word, pattern) 和 match(pattern, word) 均为 true,则表示 word 与 pattern 匹配。原因是:当 word = 'abc', pattern = 'abb' 时,match(word, pattern) 会返回 true,因此需要同时满足 match(pattern, word)。此外,可以通过判断字符串 word和pattern 的长度是否相等来进行判断,如果二者匹配,那么长度一定是相等的。
解答
方法一:哈希表
/**
* @param {string[]} words
* @param {string} pattern
* @return {string[]}
*/
var findAndReplacePattern = function(words, pattern) {
const ans = []
for (const word of words) {
if (match(word, pattern) && match(pattern, word)) {
ans.push(word)
}
}
return ans
}
/**
* @param {string} word
* @param {string} pattern
* @return {boolean}
*/
const match = (word, pattern) => {
if (word.length !== pattern.length) {
return false
}
const map = new Map()
for (let i = 0; i < word.length; ++i) {
const x = word[i], y = pattern[i]
if (!map.has(x)) {
map.set(x, y)
} else if (map.get(x) !== y) { // word 中的同一字母必须映射到 pattern 中的同一字母上
return false
}
}
return true
}
// 执行用时:60 ms, 在所有 JavaScript 提交中击败了77.78%的用户
// 内存消耗:42.7 MB, 在所有 JavaScript 提交中击败了64.44%的用户
// 通过测试用例:47 / 47
复杂度分析:
- 时间复杂度:O(nm),其中 n 是数组 words 的长度,m 是 pattern 的长度。对于每个 word 需要 O(m) 的时间检查其是否与 pattern 匹配。
- 空间复杂度:O(m)。哈希表需要 O(m) 的空间。