题目描述
代码展示
# class Solution:
# def isIsomorphic(self, s: str, t: str) -> bool:
# dict = {}
# flag = 0
# for i in range(len(s)):
# #记录,s
# if s[i] not in dict.keys():
# dict[s[i]] = t[i]
# else:
# if dict[s[i]] != t[i]:
# flag = 1
# break
# # 查找,t是否对应存在
# if flag == 0:
# return (True)
# else:
# return (False)
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
mapping_s = {}
mapping_t = {}
flag = 0
for i in range(len(s)):
if s[i] not in mapping_s.keys():
mapping_s[s[i]] = t[i]
else:
if mapping_s[s[i]] != t[i]:
flag = 1
break
if t[i] not in mapping_t.keys():
mapping_t[t[i]] = s[i]
else:
if mapping_t[t[i]] != s[i]:
flag = 1
break
if flag == 0:
return True
else:
return False
思路分解
(1)选用字典作为映射存储,每个key仅存一次;
(2)先考虑t到s的映射,然后考虑s到t的映射;
注意事项
不能只考虑一种(t到s的映射),如果这样,就像下面这种情况不能通过有些实例。