题目:
给定两个字符串 s 和 t,判断它们是否是同构的。
如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。
所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
示例 1:
输入: s = “egg”, t = “add”
输出: true
示例 2:
输入: s = “foo”, t = “bar”
输出: false
示例 3:
输入: s = “paper”, t = “title”
输出: true
说明:
你可以假设 s 和 t 具有相同的长度。
方法1:
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dic = {}
n = len(s)
for i,x in enumerate(s):
if x in dic.keys() and dic[x] != t[i]:return False
elif x not in dic.keys() and t[i] in dic.values():return False
else:dic[x] = t[i]
return True
# return len(set(zip(s,t))) == len(set(s)) == len(set(t))
方法2:(个别超时)
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
# dic = {}
# n = len(s)
# for i,x in enumerate(s):
# if x in dic.keys() and dic[x] != t[i]:return False
# elif x not in dic.keys() and t[i] in dic.values():return False
# else:dic[x] = t[i]
# return True
# return len(set(zip(s,t))) == len(set(s)) == len(set(t))
str_map1, str_map2 = {}, {}
s_list_len = len(s)
t_list_len = len(t)
if s_list_len != t_list_len:
return False
for i in range(t_list_len):
if str_map1.get(s[i]) != str_map2.get(t[i]):
return False
str_map1[s[i]] = str_map2[t[i]] = i
print(str_map1,str_map2)
return True
转载:https://blog.csdn.net/maotianyi941005/article/details/85107676
https://blog.csdn.net/qq_17550379/article/details/80586058