890. Find and Replace Pattern
- Find and Replace Pattern python solution
题目描述
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.
解析
需要对比pattern和word之间的关系。首先二者的字母数必须一致,所含有的重复字母数必须一致,映射关系必须一致。可以想到使用set()函数来得到非重复项的个数。
// An highlighted block
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
res=[]
for w in words:
if len(w)==len(pattern) and len(set(w))==len(set(pattern))==len(set(zip(w,pattern))):
res.append(w)
return res
Reference
https://leetcode.com/problems/find-and-replace-pattern/discuss/340631/Python-simple-solution