Find and Replace Pattern

1. 问题

You have a list of words and a pattern, and you want to know which words in words matches the pattern.

A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.

(Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.)

Return a list of the words in words that match the given pattern.

You may return the answer in any order.
例子

Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
Output: ["mee","aqq"]
Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. 
"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation,
since a and b map to the same letter.

2. 我的解法

var findAndReplacePattern = function(words, pattern) {
    const norPatter = toNormal(pattern)
    return words.filter( v => toNormal(v) === norPatter)
};

var toNormal = function(string) {
    let li = string.split('')
    let tem = []
    let tem2 = []
    let i = 0
    li.forEach(v => {
       let index = tem2.indexOf(v)
       if(index===-1) {
           i++
            tem.push(i)  
       } else {
           tem.push(tem[index])
       }
        tem2.push(v)
    })
    return tem.join('')
}

Runtime: 60 ms, faster than 99.18% of JavaScript online submissions for Find and Replace Pattern.

Memory Usage: 35.1 MB, less than 54.17% of JavaScript online submissions for Find and Replace Pattern.

    原文作者:lllluull
    原文地址: https://segmentfault.com/a/1190000019013512
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞