分析
用两个dict分别记录word到pattern和pattern到word的映射
然后dict的内容是个set,我们必须保证每次更新后的set的长度不会大于等于2即可满足双射
ac code
class Solution:def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:ans = []m = len(pattern)for word in words:myDict1 = defaultdict(set)myDict2 = defaultdict(set)flag = Truefor i in range(m):myDict1[pattern[i]].add(word[i])myDict2[word[i]].add(pattern[i])if len(myDict1[pattern[i]]) >= 2 or len(myDict2[word[i]]) >= 2:flag = Falsebreakif flag:ans.append(word)return ans
总结
双射的理解
dict + set应用