1. 程式人生 > >【Leetcode_總結】890. 查詢和替換模式 - python

【Leetcode_總結】890. 查詢和替換模式 - python

Q:

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

如果存在字母的排列 p ,使得將模式中的每個字母 x 替換為 p(x) 之後,我們就得到了所需的單詞,那麼單詞與模式是匹配的。

(回想一下,字母的排列是從字母到字母的雙射:每個字母對映到另一個字母,沒有兩個字母對映到同一個字母。)

返回 words 中與給定模式匹配的單詞列表。

你可以按任何順序返回答案。

示例:

輸入:
words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" 輸出:["mee","aqq"] 解釋: "mee" 與模式匹配,因為存在排列 {a -> m, b -> e, ...}。 "ccc" 與模式不匹配,因為 {a -> c, b -> c, ...} 不是排列。 因為 a 和 b 對映到同一個字母。

連結:https://leetcode-cn.com/problems/find-and-replace-pattern/

思路:建立兩個詞典,分別做對映,然後如果後面的字元在詞典中,比較其與詞典的值

程式碼:

class Solution:
    def findAndReplacePattern(self, words, pattern):
        """
        :type words: List[str]
        :type pattern: str
        :rtype: List[str]
        """
        pattern_list = [pattern for _ in range(len(words))]
        temp = zip(words, pattern_list)
        res = []
        for t in temp:
            dic = {}
            dic2 = {}
            flag = True
            for i in range(len(t[0])):
                if t[1][i] not in dic:
                    dic[t[1][i]] = t[0][i]
                else:
                    if dic[t[1][i]] != t[0][i]:
                        flag = False
                if t[0][i] not in dic2:
                    dic2[t[0][i]] = t[1][i]
                else:
                    if dic2[t[0][i]] != t[1][i]:
                        flag = False
            if flag:
                res.append(t[0])
        return res