用模式的每个字母去当做key对应单词列表的每个字母value,
如果放进dict之前检测到key已经存在,就检测Word[i][j]是否是和已经存在的value一致,不一致就代表不匹配,break检查下一个Word
还有可能不一样的key对应了一样的value,这种情况也要去掉,把dict的value去重一下,比较长度有没有变化,没有变化就代表匹配,最后输出结果。
class Solution(object):
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
result = []
a = []
flag = True
for i in range(len(words)):
dic = {}
for j in range(len(words[i])):
if pattern[j] not in dic:
dic[pattern[j]] = words[i][j]
elif dic[pattern[j]] != words[i][j]:
flag = False
break
z = set(dic.values()) if flag and len(z) == len(dic):
result.append(words[i])
a.append(dic)
flag = True
return result