问题:给定两个字符串 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)
错误提示:您的代码运行时间超出了我们的预期。检查你的时间复杂度。如果你的时间复杂度是最好的,那么超出时间限制通常是由无限循环引起的。
请问我如何改进我的代码
如果每个字符串中唯一字符的数量与它们之间对应字符的唯一对的数量相同(它们的长度也必须相同),则字符串将是同构的。
所以这个函数会简洁且更快地完成它:
def isIsomorphic(w1,w2) :
if len(w1) != len(w2): return False
return len(set(w1)) == len(set(w2)) == len(set(zip(w1,w2)))
Run Code Online (Sandbox Code Playgroud)
[编辑] 在我的计算机上,对一对 25 个字符串进行 100 万次迭代需要 3.3 秒(而 Aran-Fey 的更新代码则需要 12 秒)。