Leetcode diary: 890. Find and Replace Pattern

kevin074

kevin074

Posted on January 5, 2022

Leetcode diary: 890. Find and Replace Pattern

This is a new series where I document my struggles of leetcode questions hoping seeing however small of an audience I get gives me the motivation to continue.

This question is like the medium of medium question. It is not difficult, but requires a small degree of logical leap (I thought I did this question already but whatever).

The realization is that you could simply transform each word into a abstract representation in integers so that you don't match string by string, but by ints. This abstraction then becomes like a common language between all the words and you can just matched whether the transformedWords match the transformedPattern.

Below is my code

var findAndReplacePattern = function(words, pattern) {
    const transPattern = transform(pattern);
    const answers = [];

    words.forEach(function(word){
        if(transPattern === transform(word)) {
            answers.push(word);
        }
    });

    return answers;
};

function transform (word) {
    const letters = word.split('');
    const map = {};
    let count = 1;

    letters.forEach(function(letter, index){
        if(!map.hasOwnProperty(letter)) {
            map[letter] = count++;
        } 

        letters[index] = map[letter];
    });

    return letters.join();
}
Enter fullscreen mode Exit fullscreen mode

note that there is a small caveat to this code, which is that we are doing .join(), instead of more intuitive .join(''). The reason is that once the letters are more than 9, there could be a combination of words and patterns that somehow transforms to the same ints when joined by '', such as if t = 11, and a=1, then t could be mismatch to aa.

Let me know anything on your mind after reading through this, THANKS!

💖 💪 🙅 🚩
kevin074
kevin074

Posted on January 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related