Mooo-star / fe-algorithm

0 stars 0 forks source link

单词规律 #32

Open Mooo-star opened 1 month ago

Mooo-star commented 1 month ago

给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。

这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。

示例1:

输入: pattern = "abba", s = "dog cat cat dog" 输出: true 示例 2:

输入:pattern = "abba", s = "dog cat cat fish" 输出: false 示例 3:

输入: pattern = "aaaa", s = "dog cat cat dog" 输出: false

Mooo-star commented 1 month ago
/**
 * @param {string} pattern
 * @param {string} s
 * @return {boolean}
 */
var wordPattern = function (pattern, s) {
    const sArr = s.split(' ');

    if (sArr.length !== pattern.length) return false;

    const s2p = new Map();
    const p2s = new Map();
    const len = pattern.length;

    for (let i = 0; i < len; i++) {
        const curP = pattern[i], curS = sArr[i];
        if ((p2s.get(curP) && p2s.get(curP) !== curS) || (s2p.get(curS) && s2p.get(curS) !== curP)) {
            return false
        }

        p2s.set(curP, curS);
        s2p.set(curS, curP)
    }

    return true

};
Mooo-star commented 1 month ago

为什么用 map,因为 s 这个字符串他有 constructor 这样的关键字,烦😡!