问题:给定两个字符串 s 和 t,判断它们是否同构。
如果 s 中的字符可以替换得到 t,则两个字符串是同构的。
所有出现的字符都必须替换为另一个字符,同时保留字符的顺序。任何两个字符都不能映射到同一个字符,但一个字符可以映射到其自身。
我的代码:
def isIsomorphic(self, s, t):
# write your code here
remap = dict()
if s == t:
return True
if len(s) != len(t):
return False
for i in range(len(s)):
if s[i] not in remap.keys() and t[i] in remap.values():
return False
elif s[i] not in remap.keys():
remap[s[i]] = t[i]
else:
if remap[s[i]] != t[i]:
return False
return True
Run Code Online (Sandbox Code Playgroud)
错误提示:您的代码运行时间超出了我们的预期。检查你的时间复杂度。如果你的时间复杂度是最好的,那么超出时间限制通常是由无限循环引起的。
请问我如何改进我的代码