890. Find and Replace Pattern

1. Description

Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.
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.

2. Example

Example 1:
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.

Example 2:
Input: words = [“a”,“b”,“c”], pattern = “a”
Output: [“a”,“b”,“c”]

3. Constraints

  • 1 <= pattern.length <= 20
  • 1 <= words.length <= 50
  • words[i].length == pattern.length
  • pattern and words[i] are lowercase English letters.

4. Solutions

Hash Table

m = words.size(), n = pattern.size()
Time complexity: O(mn)
Space complexity: O(n)

class Solution {
public:
    vector<string> findAndReplacePattern(const vector<string>& words, const string &pattern) {
        vector<string> matched_string;
        for (const auto &word : words) {
            unordered_map<char, char> word_map;
            unordered_map<char, char> pattern_map;
            for (int i = 0; i < word.size(); ++i) {
                if (word_map.find(word[i]) == word_map.end() && pattern_map.find(pattern[i]) == pattern_map.end()) {
                    word_map[word[i]] = pattern[i];
                    pattern_map[pattern[i]] = word[i];
                } else if (word_map[word[i]] == pattern[i] || pattern_map[pattern[i]] == word[i]) {
                    continue;
                } else {
                    goto pass;
                }
            }

            matched_string.emplace_back(word);
            pass:;
        }

        return matched_string;
    }
};
comments powered by Disqus