41 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
*https://leetcode.cn/problems/word-pattern/?envType=study-plan-v2&envId=top-interview-150
* @param {string} pattern
* @param {string} s
* @return {boolean}
*/
const wordPattern = function (pattern, s) {
};
/*
和205类似只不过pattern中的字符映射到s中是一个单词首先处理s把s中每一个单词分离出来用数组储存之后遍历pattern和这个数组如果这个
map中存在这个key就查看当前key对应的值是否和数组的值相等如果不相等就返回false, 如果出现多个字符映射同一个字符也返回false和205一致
这里不过多解释
*/
function f1(pattern, s) {
const map = new Map();
const words = s.split(' ');
if (pattern.length !== s.length) return false;
for (let i = 0; i < pattern.length; i++) {
if (map.has(pattern[i])) {
if (map.get(pattern[i]) !== words[i]) return false;
} else {
map.set(pattern[i], words[i]);
}
}
// 检测是否出现了多个字符映射同一个字符串
const set = new Set();
// eslint-disable-next-line no-unused-vars
for (const [_, value] of map) {
if (set.has(value)) return false;
set.add(value);
}
return true;
}
/*
参考205优化思路一致可以使用数组储存对应映射查找更快使用set保存已经被映射过的单词去除最后一次遍历
*/