algos_and_structures/algocode/hash_tables/isomorphic_strings.py

74 lines
1.6 KiB
Python

class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
res = {}
already_mapped = set()
for i in range(0, len(s)):
s_word = s[i]
t_word = t[i]
if t_word in already_mapped and s_word not in res:
return False
match = res.get(s_word)
# Если не встречался символ
if not match:
# Пока слова изоморфны - мапим новую пару
res[s_word] = t_word
already_mapped.add(t_word)
continue
if match != t_word:
return False
already_mapped.add(t_word)
# Если массив закончился и не было возврата False => слова изоморфны
return True
"""
STEP 1
s = "badc"
t = "baba"
res = {}
match = None
res = {"b": "b"}
STEP 2
s = "badc"
t = "baba"
res = {"b": "b"}
match = None
res = {"b": "b", "a":"a"}
STEP 3
s = "badc"
t = "baba"
res = {"b": "b", "a":"a"}
match = None
res = {"b": "b", "a":"a", "d": "b"} <- Тут двойной маппинг => надо еще вести уже замапленые символы из t
"""
cl = Solution()
# s = "egg"
# t = "add"
# print(cl.isIsomorphic(s, t))
#
# s = "foo"
# t = "bar"
# print(cl.isIsomorphic(s, t))
#
# s = "paper"
# t = "title"
# print(cl.isIsomorphic(s, t))
#
#
# s = "p"
# t = "t"
# print(cl.isIsomorphic(s, t))
#
# s = "p"
# t = "p"
# print(cl.isIsomorphic(s, t))
s = "badc"
t = "baba"
print(cl.isIsomorphic(s, t))