leetcode 890. 查詢和替換模式 Python
阿新 • • 發佈:2018-12-20
用模式的每個字母去當做key對應單詞列表的每個字母value,
如果放進dict之前檢測到key已經存在,就檢測Word[i][j]是否是和已經存在的value一致,不一致就代表不匹配,break檢查下一個Word
還有可能不一樣的key對應了一樣的value,這種情況也要去掉,把dict的value去重一下,比較長度有沒有變化,沒有變化就代表匹配,最後輸出結果。
1 class Solution(object): 2 def findAndReplacePattern(self, words, pattern): 3 """ 4 :type words: List[str]5 :type pattern: str 6 :rtype: List[str] 7 """ 8 result = [] 9 a = [] 10 flag = True 11 for i in range(len(words)): 12 dic = {} 13 for j in range(len(words[i])): 14 if pattern[j] not in dic: 15 dic[pattern[j]] = words[i][j]16 elif dic[pattern[j]] != words[i][j]: 17 flag = False 18 break 19 z = set(dic.values()) 20 21 if flag and len(z) == len(dic): 22 result.append(words[i]) 23 a.append(dic) 24 flag = True25 return result