41 lines
1.3 KiB
JavaScript
41 lines
1.3 KiB
JavaScript
/**
|
||
*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保存已经被映射过的单词,去除最后一次遍历
|
||
*/
|