【LeetCode】890. Find and Replace Pattern 解题报告(Python)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuxuemingzhu/article/details/82014687

【LeetCode】890. Find and Replace Pattern 解题报告(Python)

标签(空格分隔): LeetCode

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/find-and-replace-pattern/description/

题目描述:

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. 1 <= words.length <= 50
  2. 1 <= pattern.length = words[i].length <= 20

题目大意

我觉得应该把题目中的permutation理解为“映射”更为合适。

这样的话,题目意思就是找出words中所有满足映射关系的单词。映射关系由pattern给出,即要求words中的单词和pattern中的每个字符的对应关系应该完全一致。

解题方法

既然考到映射,那么应该是使用HashMap来搞定,直接把映射一一的放入map中,如果出现过这个映射的话,就看新的对应关系和原来的映射是否相同。代码中使用了set来加速判断。

注意题目中给出了一个细节,就是words里面的每个word都和pattern长度相同,省去了判断长度的过程。

代码如下:

class Solution(object):
    def findAndReplacePattern(self, words, pattern):
        """
        :type words: List[str]
        :type pattern: str
        :rtype: List[str]
        """
        ans = []
        set_p = set(pattern)
        for word in words:
            if len(set(word)) != len(set_p):
                continue
            fx = dict()
            equal = True
            for i, w in enumerate(word):
                if w in fx:
                    if fx[w] != pattern[i]:
                        equal = False
                        break
                fx[w] = pattern[i]
            if equal:
                ans.append(word)
        return ans

参考资料:无

日期

2018 年 8 月 24 日 ———— Keep fighting!

猜你喜欢

转载自blog.csdn.net/fuxuemingzhu/article/details/82014687
今日推荐