890. Find and Replace Pattern

Link: https://leetcode.com/problems/find-and-replace-pattern/

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.

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.

Note:

  • 1 <= words.length <= 50
  • 1 <= pattern.length = words[i].length <= 20

題目翻譯:

你有一個單詞列表和一個模式,你想知道單詞中哪些單詞與模式匹配。

如果存在字母 p 的排列,則字符與模式匹配,以便在用 p(x)替換模式中的每個字母 x 後,我們得到所需的字。

(回想一下,字母的排列是從字母到字母的雙向排列:每個字母都映射到另一個字母,沒有兩個字母映射到同一個字母。)
返回與給定模式匹配的單詞列表。

您可以按任何順序返回答案

程式思路:

建構一張 1 對 1 的表,不可多對 1,不可 1 對多。 有點線性函數的概念。用 map 檢查有沒有 1 對多,用 set 檢查有沒有多對 1。

class Solution {
public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        vector <string > result;
        for(auto word : words)
        {
            int i = 0;
            unordered_map <char, char> table;
            unordered_set <char> mark;
            for(i = 0; i< pattern.length(); i++)
            {
                auto ret = table.insert(std::pair <char,char> (pattern[i],word[i]));
                if(ret.second == false) //already exist
                {
                    if(table[pattern[i]] != word[i])
                        break;
                }else
                {
                    auto ret = mark.insert(word[i]);
                    if(ret.second == false)
                        break;
                }
            }
            if(i == pattern.length())
                result.emplace_back(word);
        }
        return result;
    }
};

  目錄