[
string
hash table
]
Leetcode 0890. Find and Replace Pattern
Problem statement
https://leetcode.com/problems/find-and-replace-pattern/
Solution
Let us just reuse problem 205 Isomorphic Strings - idea is to keep two dictionaries and check for each pair of symbols if we can create connection, where the question is to do exactly the same but for one pair of words. See also problem 0290 Word Pattern, here I use exaclty the same logic, but instead of words we have letters.
#### Complexity
If length of each word is k
and we have n
of them, then time and space complexity will be O(nk)
.
Code
class Solution:
def findAndReplacePattern(self, words, pattern) :
def isIsomorphic(s, t):
d1, d2 = {}, {}
for i, j in zip(s, t):
if i not in d1:
if j in d2: return False
else:
d1[i] = j
d2[j] = i
elif d1[i] != j: return False
return True
return [w for w in words if isIsomorphic(w, pattern)]