[
string
hash table
]
Leetcode 0205. Isomorphic Strings
Problem statement
https://leetcode.com/problems/isomorphic-strings/
Solution
Go symbol by symbol and add direct and inverse connections to hash tables d1 and d2.
- If
i not in d1andj in d2, it means, that something is wrong, we have casea -> x,b -> x, returnFalse. - If
i not in d1andj not in d2, it means that we see this pair first time, update both dictionaries. - If
i in d1andd1[i] != j, it means, that we havea -> x,a -> y, returnFalse. - In the end return
Trueif we did not return anyghing before.
Complexity
Time complexity is O(n), space complexity is O(m), where m is size of alphabet to keep dictionaries.
Code
class Solution:
def isIsomorphic(self, 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