版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013596119/article/details/81982606
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
Answer:
用dict保存已经配对的两个字符,如果w中的字符匹配了新的p字符,则失败,如果w中的新字符匹配了旧的p字符则失败
扫描二维码关注公众号,回复:
2968931 查看本文章
class Solution(object):
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
result=[]
for w in words:
dict_char={}
match=True
for i in range(len(w)):
if dict_char.has_key(w[i]):
if dict_char[w[i]]!=pattern[i]:
match=False
break
else:
if pattern[i] in dict_char.values():
match=False
break
dict_char[w[i]]=pattern[i]
if match:
result.append(w)
return result